I recently just used dcast (in the reshape2 package) to condense my data frame from long format to wide (since I needed counts). Now, I need to fill in the combination that do NOT exist with a 0. I imagine I could do something with expand.grid in the base package but I'm not sure how (?) since I don't just want every combo but I also already have some counts. An example of what I have:
AgeGroup Sex Month Count
10 F 2 4
10 F 6 1
11 M 6 2
And what I would like:
AgeGroup Sex Month Count
10 F 2 4
10 F 3 0
10 F 4 0
10 F 5 0
10 F 6 1
Edit in response to Anada's comment:
Minimum reproducible data/code:
library(reshape2)
Sex <- c('M', 'F', 'F', 'F', 'M')
County <- c(41, 65, 35, 49, 41)
AgeGroup <- c(11, 10, 18, 11, 11)
Month <- c(1, 1, 2, 4, 1)
Count <- rep(1, 5)
DF <- cbind.data.frame(Sex, County, AgeGroup, Month, Count)
DF <-dcast(DF, County+Sex+Month+AgeGroup~Count,
value.var="Count", length)
names(DF)[names(DF)=='1'] <- 'Count'
Note that in this example two observations are identical on purpose to demonstrate how I want to collapse things. I also don't know why but dcast renames the Count column so I have to change the name at the end.