我想问你是否有办法根据多个变量的组合进行过滤。更具体一点:
library(dplyr)
library(plyr)
library(data.table)
data <- iris %>% cbind( group = rep(c("a", "b", "c"), nrow(iris))) %>% as.data.table()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species group
1: 5.1 3.5 1.4 0.2 setosa a
2: 4.9 3.0 1.4 0.2 setosa b
3: 4.7 3.2 1.3 0.2 setosa c
4: 4.6 3.1 1.5 0.2 setosa a
5: 5.0 3.6 1.4 0.2 setosa b
6: 5.4 3.9 1.7 0.4 setosa c
我希望根据以下数据表过滤它们
filter <- data.table(Species = c("setosa", "versicolor", 'setosa'), group = c('a', "b", 'c'))
Species group filter1
1: setosa a setosa a
2: versicolor b versicolor b
3: setosa c setosa c
我可以这样做:
data[paste(Species, group) %in% filter[, filter1 := paste(Species, group)]$filter1]
但是我想知道是否有更有效/更快/更容易的方式: 也许是这样的东西:
data[.(Species, group) %in% filter] # does not work
答案 0 :(得分:3)
在这种情况下,您可以
data[filter, on=names(filter), nomatch=0]
请参阅 Perform a semi-join with data.table用于类似的过滤连接。