Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset elements in a list based on a logical condition

How can I subset a list based on a condition (TRUE, FALSE) in another list? Please, see my example below:

l <- list(a=c(1,2,3), b=c(4,5,6,5), c=c(3,4,5,6)) l $a [1] 1 2 3  $b [1] 4 5 6 5  $c [1] 3 4 5 6  cond <- lapply(l, function(x) length(x) > 3) cond $a [1] FALSE  $b [1] TRUE  $c [1] TRUE  > l[cond] 

Error in l[cond] : invalid subscript type 'list'

like image 696
jrara Avatar asked Aug 04 '11 12:08

jrara


People also ask

How do you subset elements in a list?

To subset these sub-elements we can use sapply function and use c to subset the number of corresponding sub-elements. For example, if we have a list that contains five elements and each of those elements have ten sub-elements then we can extract 1, 2, 3 etc elements from sub-elements.

How do I create a subset of a vector in R?

The way you tell R that you want to select some particular elements (i.e., a 'subset') from a vector is by placing an 'index vector' in square brackets immediately following the name of the vector. For a simple example, try x[1:10] to view the first ten elements of x.


2 Answers

This is what the Filter function was made for:

Filter(function(x) length(x) > 3, l) $b [1] 4 5 6 5  $c [1] 3 4 5 6 
like image 91
Jason Morgan Avatar answered Oct 03 '22 10:10

Jason Morgan


Another way is to use sapply instead of lapply.

cond <- sapply(l, function(x) length(x) > 3) l[cond] 
like image 32
PatrickR Avatar answered Oct 03 '22 10:10

PatrickR