user3354212 - 1 year ago 52

R Question

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`

`list2`

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 Source

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
```