如何在R中对表对象进行子集操作?

9

如何根据值对表进行子集,并返回这些值?这只会返回索引:

with(chickwts, table(feed))
with(chickwts, table(feed)) > 11
which(with(chickwts, table(feed)) > 11)

输出

> with(chickwts, table(feed))
feed
   casein horsebean   linseed  meatmeal   soybean sunflower 
       12        10        12        11        14        12 
> with(chickwts, table(feed)) > 11
feed
   casein horsebean   linseed  meatmeal   soybean sunflower 
     TRUE     FALSE      TRUE     FALSE      TRUE      TRUE 
> which(with(chickwts, table(feed)) > 11)
   casein   linseed   soybean sunflower 
        1         3         5         6 
3个回答

6
您需要两次使用计算出的值,因此使用一个中间变量会很有用:
x <- with(chickwts, table(feed))
x[x>11]
feed
   casein   linseed   soybean sunflower 
       12        12        14        12 

1
或者,使用有些重复的代码:with(chickwts, table(feed)[table(feed) > 11]) - A5C1D2H2I1M1N2O1R2T1

6
这里有另一种方法,利用Filter函数:

Filter(function(x) x > 11, with(chickwts, table(feed)))
feed
   casein   linseed   soybean sunflower 
       12        12        14        12 

3

使用基本功能的另一种选项:

subset(data.frame(table(chickwts$feed)), Freq > 11)

结果:

       Var1 Freq
1    casein   12
3   linseed   12
5   soybean   14
6 sunflower   12

使用 dplyr 包:
library(dplyr)
chickwts %>% 
  count(feed) %>%
  filter(n > 11) 

结果:

Source: local data frame [4 x 2]

       feed  n
1    casein 12
2   linseed 12
3   soybean 14
4 sunflower 12

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接