How to subset a table object in R?

r
15,415

Solution 1

You need to use the computed value twice, so its useful to use an intermediate variable:

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

Solution 2

Here is an other approach making use of the Filter function:

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

Solution 3

Another option using base functions:

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

Result:

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

Using the dplyr package:

library(dplyr)
chickwts %>% 
  count(feed) %>%
  filter(n > 11) 

Result:

Source: local data frame [4 x 2]

       feed  n
1    casein 12
2   linseed 12
3   soybean 14
4 sunflower 12
Share:
15,415

Related videos on Youtube

jrara
Author by

jrara

Updated on September 16, 2022

Comments

  • jrara
    jrara over 1 year

    How can I subset a table based on values and return those values? This returns just indices:

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

    Output

    > 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 
    
  • A5C1D2H2I1M1N2O1R2T1
    A5C1D2H2I1M1N2O1R2T1 over 11 years
    Or, with somewhat repetitious code: with(chickwts, table(feed)[table(feed) > 11])