user3354212 user3354212 - 3 months ago 9
R Question

how to eliminate elements from all vectors in a list that are present in a vecor in r

I have a list contain different vectors with different length

list1 <- list(a = 1:10, b = 3:20, c = c(1,3,7, 9,18,20,24,28))


I would like to eliminate any elements from all vectors in
list1
that are present in a vector

d <- c(1,3,7,8,20)


I expect the result as:

list(a = c(2,4:6,9:10), b = c(4:6,9:19), c = c(9,18,24,28))

Answer

For example

lapply(list1, setdiff, d)

gives

$a
[1]  2  4  5  6  9 10

$b
 [1]  4  5  6  9 10 11 12 13 14 15 16 17 18 19

$c
[1]  9 18 24 28

Read ?setdiff for related functions.