Reputation: 85
I have a two lists of lists generated by the following function:
a <- replicate(10, sample(1:100,size=10), simplify=FALSE)
b <- replicate(10, sample(1:100,size=10), simplify=FALSE)
Is there a way to remove numbers in 'b' lists from corresponding lists in 'a' so if:
a[1] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
b[1] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
then the output would ideally be
c[1] = {1}
I was trying to do something like this but it didn't work:
for(i in 1:10){
index <- which( names(a[i]) %in% b[i])
a[i][-index]
}
Thanks ahead of time.
Upvotes: 1
Views: 166
Reputation: 8880
additional solution
a <- list(c(1:10))
b <- list(c(2:11))
purrr::map2(.x = a, .y = b, .f = dplyr::setdiff)
Upvotes: 1
Reputation: 886998
We can use Map
with setdiff
Map(setdiff, b, a)
If it is the opposite
Map(setdiff, a, b)
Or another option is vsetdiff
to preserve duplicate elements
library(vecsets)
Map(vsetdiff, a, b)
Or use %in%
and negate (!
)
Map(function(x, y) x[!x %in% y], a, b)
Or using for
loop
for(i in seq_along(a)) a[[i]] <- a[[i]][!a[[i]] %in% b[[i]]]
Upvotes: 1