【问题标题】:How to subset a table object in R?如何在 R 中对表对象进行子集化?
【发布时间】:2012-10-10 00:04:38
【问题描述】:

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

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 

【问题讨论】:

    标签: r


    【解决方案1】:

    您需要使用两次计算值,因此使用中间变量很有用:

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

    【讨论】:

    • 或者,有些重复的代码:with(chickwts, table(feed)[table(feed) &gt; 11])
    【解决方案2】:

    这是使用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
      

      【讨论】:

        猜你喜欢
        • 2019-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多