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'
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.
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.
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
Another way is to use sapply
instead of lapply
.
cond <- sapply(l, function(x) length(x) > 3) l[cond]
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