Reputation: 19704
This might seem like a silly question, but after spending some time looking for an (easy) solution, I could not find it.
I have a list of vectors:
l <- list(c(1, 2), c(5, 10))
and I want to test whether a given vector --- for instance, c(1, 2)
--- is in that list. I thought the "straightforward" approach would work:
c(1, 2) %in% l
but that returns
[1] FALSE FALSE
In the end I found the following solution:
any(sapply(l, function(x) { all(x == c(1, 2)) }))
but it is quite cumbersome, so I really wonder if that is the simplest option. Is there any simpler way to test for a vector in a list of vectors?
Upvotes: 1
Views: 79
Reputation: 17412
Since you are dealing with objects the ==
operator is not ideal. A slightly simpler approach is:
any(sapply(l, identical, y=c(1,2)))
The %in%
operator doesn't work because it is a call to the function match
. It reads l
as a vector. In other words, what it's doing is:
for(i in 1:length(c(1,2)))
c(1,2)[i]==l[[i]]
Upvotes: 3