Reputation: 562
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
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
Reputation: 7190
As my previous comment, here is a (more robust) solution:
which(foo == TRUE)
[1] 1 2 4
Upvotes: 2