如何使用R的data.table包来对键值的否定进行子集化?

时间:2012-04-03 15:29:38

标签: r data.table

R的data.table包根据键提供快速的值子集。

所以,例如:

set.seed(1342)

df1 <- data.table(group = gl(10, 10, labels = letters[1:10]),
                  value = sample(1:100))
setkey(df1, group)

df1["a"]

将返回df1中所有行,其中group ==“a”。

如果我希望df1中的所有行group != "a",该怎么办?使用data.table是否有简明的语法?

2 个答案:

答案 0 :(得分:8)

我想你回答了自己的问题:

> nrow(df1[group != "a"])
[1] 90
> table(df1[group != "a", group])

 a  b  c  d  e  f  g  h  i  j 
 0 10 10 10 10 10 10 10 10 10 

对我来说似乎很简洁?

编辑来自MATTHEW:根据评论这是一个矢量扫描。有一个不能加入习语 herehere以及feature request #1384,以便更轻松。

编辑:feature request #1384在data.table 1.8.3

中实现
df1[!'a']

# and to avoid the character-to-factor coercion warning in this example (where
# the key column happens to be a factor) :
df1[!J(factor('a'))]

答案 1 :(得分:1)

我会得到所有不是“a”的键:

df1[!(group %in% "a")]

这实现了你想要的吗?