Suppose I\'ve got the following data.table
:
dt <- data.table(id=c(1,1,1,1,1,1,2,2,2,2),
wday=c(\"mon\",\"tue\",\"wed\",\"thu\",\"
One other possilibity with match and ddply :
FUN <- function(x) {
y <- x$val[match(c("mon", "tue", "wed", "thu", "fri", "sat", "sun"), x$wday, nomatch=NA)]
y[is.na(y)] <- 0
y <- data.frame(wday=c("mon", "tue", "wed", "thu", "fri", "sat", "sun"), val=y)
y
}
ddply(dt, .(id), FUN)
One straightforward way I could think of right now is to use expand.grid
to get all combinations and then use that to subset with allow.cartesian = TRUE
:
setkey(dt, "id", "wday")
vals <- c("mon", "tue", "wed", "thu", "fri", "sat", "sun")
idx <- expand.grid(vals, unique(dt$id))[, 2:1]
dt[J(idx), allow.cartesian=TRUE]
# id wday val
# 1: 1 mon 2
# 2: 1 tue 3
# 3: 1 wed 5
# 4: 1 thu 8
# 5: 1 fri 6
# 6: 1 sat 2
# 7: 1 sun NA
# 8: 2 mon 3
# 9: 2 tue 4
# 10: 2 wed NA
# 11: 2 thu 2
# 12: 2 fri 6
# 13: 2 sat NA
# 14: 2 sun NA
Alternatively, it is possible to directly build the idx
data table with CJ
:
dt[CJ(unique(dt$id),vals), allow.cartesian=TRUE]