Reputation: 1480
I have a list which contains different elements and a vector which list some of the elements, I would like to find out in which list index number does each element fall into.
x <- list ( c ( 1,2 ), c( 3,4 ), c( 5,6 ), c( 7,8 ), c( 9,10 ) , c( 11,12 ))
y <- c( 2,3,4,6,8,10,11,12 )
# Desired Output in a list
[[1]]
[1] 2
[[2]]
[1] 3 4
[[3]]
[1] 6
[[4]]
[1] 8
[[5]]
[1] 10
[[6]]
[1] 11 12
If both were two vectors I would use intersect and which as to find out the possition in x of elements in y
Upvotes: 0
Views: 290
Reputation: 513
lapply combined with %in% will get you the answer:
lapply(x,function(i){i[i%in%y]})
lapply applies the function to each list element of 'x', the %in% evaluates whether each element of 'i' is in 'y'.
Upvotes: 1
Reputation: 93813
Use Map
or lapply
Map(intersect, x, list(y))
#or
lapply(x, intersect, y)
#[[1]]
#[1] 2
#
#[[2]]
#[1] 3 4
#
#[[3]]
#[1] 6
#
#[[4]]
#[1] 8
#
#[[5]]
#[1] 10
#
#[[6]]
#[1] 11 12
Upvotes: 2