user1658170
user1658170

Reputation: 858

value match within a list

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

Answers (2)

YOLO
YOLO

Reputation: 21709

You can do:

val = 3
names(lst)[sapply(lst, function(x) val %in% x)]

[1] "A" "B"

Explanation:

  1. sapply(lst, function(x) val %in% x)): returns a vector of boolean values
  2. names: get the names according to boolean values

Upvotes: 4

R. Schifini
R. Schifini

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

Related Questions