Efficiently inserting default missing rows in a data.table

前端 未结 2 1148
一整个雨季
一整个雨季 2021-01-14 00:25

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\",\"         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 00:49

    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)
    

提交回复
热议问题