user3354212 user3354212 - 3 months ago 10
R Question

how to find elements from a list that are not present in another list in r

I have two lists that have the same vectors but with different length

list1 <- list(a = 1:10, b = 3:20)
list2 <- list(a = c(2,5,8), b = c(3,5,11,20))


I would like to find elements from each vector in
list1
that are not present in the corresponding vector in
list2
. There are similar questions answered for other scripts instead of R.

I expect the final list is

lst <- list(a=c(1,3,4,6,7,9,10),b=c(4,6:10,12:19))


Thank you for help.

Answer

We can use

mapply(setdiff,list1,list2)
#$a
#[1]  1  3  4  6  7  9 10

#$b
#[1]  4  6  7  8  9 10 12 13 14 15 16 17 18 19