How to use an unknown number of key columns in a data.table

前端 未结 2 553
后悔当初
后悔当初 2021-01-13 22:08

I want to do the same as explained here, i.e. adding missing rows to a data.table. The only additional difficulty I\'m facing is that I want the number of key columns, i.e.

2条回答
  •  礼貌的吻别
    2021-01-13 22:34

    I've never used the data.table package, so forgive me if I miss the mark here, but I think I've got it. There's a lot going on here. Start by reading up on do.call, which allows you to evaluate any function in a sort of non-traditional manner where arguments are specified by a supplied list (where each element is in the list is positionally matched to the function arguments unless explicitly named). Also notice that I had to specify min(df$variable) instead of just min(variable). Read Hadley's page on scoping to get an idea of the issue here.

    CJargs <- lapply(df[, idCols], unique)
    names(CJargs) <- NULL
    CJargs[[length(CJargs) +1]] <- seq(from=min(df$variable), to=max(df$variable))
    DT[do.call("CJ", CJargs),nomatch=NA]
    

提交回复
热议问题