NBK
NBK

Reputation: 905

compare elements of two lists by position to test common strings in r

(Here and here similar questions, but for python.)

I have two lists of equal length, each list containing character vectors. I want to contrast the lists, position by position, to test whether they have common elements.

list_1 <- list(c("a","b"), c("a","c"))
list_2 <- list(c("a","x"), c("p","q"))

> list_1
[[1]]
[1] "a" "b"

[[2]]
[1] "a" "c"

> list_2
[[1]]
[1] "a" "x"

[[2]]
[1] "p" "q"

This is likely a lapply problem, but I'm not sure how to tackle it. Here's an attempt that does not work:

> lapply(list_1, function(x){any(x %in% list_2)})
[[1]]
[1] FALSE

[[2]]
[1] FALSE

The expected solution is:

[[1]]
[1] TRUE

[[2]]
[1] FALSE

Help?

Upvotes: 2

Views: 766

Answers (1)

Nate
Nate

Reputation: 10671

You want ?mapply, which allows you to iterate, or apply, an anonymous function in "parallel" across multiple (the "m") lists.

mapply(function(x, y) {any(x %in% y)}, list_1, list_2)

You could extend it to more than 2 lists if you added another argument to the anon function.

Upvotes: 3

Related Questions