[英]How to remove a list of lists from another list of lists in R?
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”中的相应列表中删除“b”列表中的数字,如果:
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.提前致谢。
We can use Map
with setdiff
我们可以使用
Map
和setdiff
Map(setdiff, b, a)
If it is the opposite如果是相反的
Map(setdiff, a, b)
Or another option is vsetdiff
to preserve duplicate elements或者另一个选项是
vsetdiff
来保留重复元素
library(vecsets)
Map(vsetdiff, a, b)
Or use %in%
and negate ( !
)或者使用
%in%
并否定( !
)
Map(function(x, y) x[!x %in% y], a, b)
Or using for
loop或者使用
for
循环
for(i in seq_along(a)) a[[i]] <- a[[i]][!a[[i]] %in% b[[i]]]
additional solution附加解决方案
a <- list(c(1:10))
b <- list(c(2:11))
purrr::map2(.x = a, .y = b, .f = dplyr::setdiff)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.