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!
Lists in R can be subsetted using all three of the operators mentioned above, and all three are used for different purposes. The [[ operator can be used to extract single elements from a list. Here we extract the first element of the list.
Subsetting in R is a useful indexing feature for accessing object elements. It can be used to select and filter variables and observations. You can use brackets to select rows and columns from your dataframe.
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.
There are three subsetting operators, [[ , [ , and $ . Subsetting operators interact differently with different vector types (e.g., atomic vectors, lists, factors, matrices, and data frames). Subsetting can be combined with assignment.
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.
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