Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subset a table object in R?

Tags:

r

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 
like image 291
jrara Avatar asked Oct 19 '12 11:10

jrara


People also ask

How do you subset an object in R?

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.

How do I subset specific data in R?

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] .

How do I subset specific rows in R?

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.


2 Answers

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 
like image 150
James Avatar answered Oct 30 '22 17:10

James


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 
like image 38
johannes Avatar answered Oct 30 '22 15:10

johannes