子集data.table列独立

时间:2016-10-11 12:01:03

标签: r data.table subset

我从下面的表dt开始,尝试按列表keys对其列进行子集化:

library(data.table)

set.seed(123)

randomchar <- function(n, w){
  chararray <- replicate(w, sample(c(letters, LETTERS), n, replace = TRUE))
  apply(chararray, 1, paste0, collapse = "")
}

dt <- data.table(x = randomchar(1000, 3),
                 y = randomchar(1000, 3),
                 z = randomchar(1000, 3),
                 key = c("x", "y", "z"))

keys <- with(dt, list(x = sample(x, 501),
              y = sample(y, 500),
              z = sample(z, 721)))

我可以通过循环获得我想要的结果:

desired <- copy(dt)

for(i in seq_along(keys)){
  keyname <- names(keys)[i]
  desired <- desired[get(keyname) %in% keys[[i]]]
}

desired

问题是 - 是否有更多data.table惯用方法来执行此子集?

我尝试使用CJdt[CJ(keys)],但这需要很长时间。

1 个答案:

答案 0 :(得分:4)

如何在此蒙版上构建蒙版并过滤dt

dt[Reduce(`&`, Map(function(key, col) col %in% key, keys, dt)),]