Providing the correct match for a list in a list of lists in R

Viewed 159

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 Lis very large, I need a faster solution. (And is a list even the right choice here?)

3 Answers

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

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)

Perhaps you can try mapply like below

> which(mapply(identical, L, list(l)))
[1] 1
Related