Reputation: 858
I have a list such as created by this code:
lst <- list(c(c(1,2,3)), c(3,4,5))
names(lst) <- c("A","B")
and which looks like this:
> lst
$`A`
[1] 1 2 3
$B
[1] 3 4 5
How can I value match in a way that returns true or false for each list element? How can I then extract the names of the lists for which this is true. So in this example if I wish to value match "2" I would want to return
[1] TRUE, FALSE
and then I would like to return the name of the list where this is true so:
[1] "A"
If i was value matching 3 I would want:
[1] TRUE, TRUE
and
[1] "A", "B"
I can't find a way to achieve this.
Thanks.
Upvotes: 0
Views: 613
Reputation: 21709
You can do:
val = 3
names(lst)[sapply(lst, function(x) val %in% x)]
[1] "A" "B"
Explanation:
sapply(lst, function(x) val %in% x))
: returns a vector of boolean valuesnames
: get the names according to boolean valuesUpvotes: 4
Reputation: 9313
Try this:
lst = list(A = c(c(1,2,3)), B = c(3,4,5))
searchValue = 2
z = sapply(lst, function(x){ searchValue%in%x })
Results:
> z
A B
TRUE FALSE
> names(z)[z]
[1] "A"
Upvotes: 2