简体   繁体   中英

Subset data.table columns independently

I'm starting with the below table dt and try to subset its column by the list 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)))

I can get the result I want by using a loop:

desired <- copy(dt)

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

desired

The question is - Is there a more data.table idiomatic way to do this subset?

I tried using CJ : dt[CJ(keys)] , but it takes a very long time.

怎么样在这个面具上构建一个蒙版并过滤dt

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM