Skip to content
Prev 319220 / 398506 Next

How to 'extend' a data.frame based on given variable combinations ?

... okay, I found a solution:

set.seed(1)
x <- data.frame(group = c(rep("A", 4), rep("B", 3)),
                year  = c(2001,      2003, 2004, 2005,
                                     2003, 2004, 2005),
                value = rexp(7))

tply <- as.data.frame(as.table(tapply(x$value, list(x$group, x$year), FUN=length)),
                      nm=colnames(x)) # => 2002 missing
names(tply) <- c("group", "year", "num")
grid <- expand.grid(group = LETTERS[1:2], year=2001:2005) # all variable combinations
tply <- merge(grid, tply, by=c("group", "year"), all=TRUE) # merge the two data.frames
tply$num[is.na(tply$num)] <- 0
tply


Marius Hofert <> writes: