rdevn00b
rdevn00b

Reputation: 562

Subset list based on TRUE/FALSE

Say I have a list

> foo

[[1]]
[1] TRUE

[[2]]
[1] TRUE

[[3]]
[1] FALSE

[[4]]
[1] TRUE

How do I find which values return TRUE, so that I get a list like

[1] 1 2 4

Thanks!

Upvotes: 6

Views: 11651

Answers (2)

user1357015
user1357015

Reputation: 11696

All you need to do is unlist it and ask which ones are TRUE via which.

which(unlist(foo))

> foo <- list(TRUE, TRUE, FALSE, TRUE)
> which(unlist(foo))
[1] 1 2 4

@Per the comment:

In case you're not sure all your elements are of the same type, you can also do: which(foo == TRUE)

Personally, I'd rather it throw an error as implicitly, in my mind, if I do a query over all the elements, I assume each one is comparable. However, the concern is valid.

Upvotes: 6

SabDeM
SabDeM

Reputation: 7190

As my previous comment, here is a (more robust) solution:

which(foo == TRUE)
[1] 1 2 4

Upvotes: 2

Related Questions