Reputation: 569
I have a list of lists in R:
a <- list(x=0, y=c(1,2,3), z=4)
b <- list(x=1, y=c(1,2,3), z=44)
c <- list(x=2, y=c(1,2,3), z=444)
L <- list(a,b,c)
For a given list, say
l <- list(x=0, y=c(1,2,3), z=4)
I know want to find the correct index of L
where we find the corresponding list that equals l
.
Of course, I can use a loop, but since L
is very large, I need a faster solution.
(And is a list even the right choice here?)
Upvotes: 5
Views: 899
Reputation: 102710
Perhaps you can try mapply
like below
> which(mapply(identical, L, list(l)))
[1] 1
Upvotes: 0
Reputation: 887891
We can use stack
with identical
from base R
which(sapply(L, function(x) identical(stack(l), stack(x))))
#[1] 1
Or more compactly
which(sapply(L, identical, l))
#[1] 1
Upvotes: 4
Reputation: 73702
Using mapply
to compare each element one by one with l
. If you unlist
it, all
should be TRUE
. Using which
around an sapply
finally gives the number of the matching element.
f <- function(x) all(unlist(mapply(`==`, x, l)))
which(sapply(L, f))
# [1] 1
Data:
L <- list(list(x = 0, y = c(1, 2, 3), z = 4), list(x = 1, y = c(1,
2, 3), z = 44), list(x = 2, y = c(1, 2, 3), z = 444))
l <- list(x = 0, y = c(1, 2, 3), z = 4)
Upvotes: 1