Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset list based on TRUE/FALSE

Tags:

r

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!

like image 323
rdevn00b Avatar asked Aug 21 '15 17:08

rdevn00b


People also ask

Can you subset a list in R?

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.

What is Subsetting in R?

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.

How do you subset 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.

What are the three subsetting operators in R?

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.


1 Answers

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.

like image 108
user1357015 Avatar answered Oct 13 '22 02:10

user1357015