Nyiannos
Nyiannos

Reputation: 99

return a vector from a list based on a condition

I have a list

alist <- list(c(1,2,9),c(4,5,4),c(3,11,19))

and a constant

value <- 4

I want to return the vector from the list in which the first element of the vector equals the constant (i.e., (4,5,4)). I'd like to do this in base R. Can anyone help?

Upvotes: 1

Views: 29

Answers (1)

akrun
akrun

Reputation: 886948

We can loop through the list with sapply, extract the first element, compare it with 'value' to get a logical vector and subset the 'alist' based on that

alist[sapply(alist, `[`, 1) == value]

Or with Filter

Filter(function(x) x[1] == value, alist)

If we use purrr

purrr::keep(alist, ~ .x[1] == value)

Upvotes: 4

Related Questions