2012-10-19 35 views
5

如何基於值對錶進行子集並返回這些值?這將返回剛剛指數:如何在R中對錶對象進行子集化?

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 

回答

5

您需要使用計算值的兩倍,因此它使用一箇中間變量有用:

x <- with(chickwts, table(feed)) 
x[x>11] 
feed 
    casein linseed soybean sunflower 
     12  12  14  12 
+0

啊,是的,當然,謝謝! – jrara

+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 
+0

很好的使用'Filter()'。 – A5C1D2H2I1M1N2O1R2T1

1

使用基函數另一種選擇:

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 
相關問題