I have a dataframe like so:
Title Female Male Asian HispanicLatino White
1 Title1 2 3 1 1 3
2 Title2 1 5 NA 1 5
3 Title3 NA 2 NA NA 2
I want to expand this out so that there are two rows for Female in Title 1, and three Male, as well as expanding the other columns (I have many more columns).
I've tried various different things, and the following technically works but is not ideal.
df[is.na(df)] <- 0
dfM <- uncount(df, df$Male)
dfM$Sex <- "M"
dfF <- uncount(df, df$Female)
dfF$Sex <- "F"
df <- rbind.fill(dfF, dfM)
Which produces
Title Female Male Asian HispanicLatino White Sex
1 Title1 2 3 1 1 3 F
2 Title1 2 3 1 1 3 F
3 Title2 1 5 0 1 5 F
4 Title1 2 3 1 1 3 M
5 Title1 2 3 1 1 3 M
6 Title1 2 3 1 1 3 M
7 Title2 1 5 0 1 5 M
8 Title2 1 5 0 1 5 M
9 Title2 1 5 0 1 5 M
10 Title2 1 5 0 1 5 M
11 Title2 1 5 0 1 5 M
12 Title3 0 2 0 0 2 M
13 Title3 0 2 0 0 2 M
Curious to see if there is a much easier way to do this.
Here is some data:
dput(df)
structure(list(Title = structure(1:3, .Label = c("Title1",
"Title2", "Title3"), class = "factor"), Female = c(2L, 1L, NA
), Male = c(3L, 5L, 2L), Asian = c(1L, NA, NA), HispanicLatino = c(1L,
1L, NA), White = c(3L, 5L, 2L)), .Names = c("Title", "Female",
"Male", "Asian", "HispanicLatino", "White"), class = "data.frame", row.names = c(NA,
-3L))