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 
                Method 2: Subsetting in R Using [[ ]] Operator [[ ]] operator is used for subsetting of list-objects. This operator is the same as [ ] operator but the only difference is that [[ ]] selects only one element whereas [ ] operator can select more than 1 element in a single command.
The most general way to subset a data frame by rows and/or columns is the base R Extract[] function, indicated by matched square brackets instead of the usual matched parentheses. For a data frame named d the general format is d[rows, columms] .
By using bracket notation on R DataFrame (data.name) we can select rows by column value, by index, by name, by condition e.t.c. You can also use the R base function subset() to get the same results. Besides these, R also provides another function dplyr::filter() to get the rows from the DataFrame.
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 
                        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 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With