删除R中列表中的元素

我想删除列表的一部分,它是列表其他部分的完整集合.例如,B与A相交,E与C相交,因此应删除B和E.

MyList <- list(A=c(1,2,3,4,5), B=c(3,4,5), C=c(6,7,8,9), E=c(7,8))
MyList
$A
[1] 1 2 3 4 5
$B
[1] 3 4 5
$C
[1] 6 7 8 9
$E
[1] 7 8

MyListUnique <- RemoveSubElements(MyList)
MyListUnique
$A
[1] 1 2 3 4 5
$C
[1] 6 7 8 9

有任何想法吗 ?知道这个功能吗?

最佳答案 只要您的数据不是太大,您就可以使用如下方法:

# preparation
MyList <- MyList[order(lengths(MyList))]
idx <- vector("list", length(MyList))
# loop through list and compare with other (longer) list elements
for(i in seq_along(MyList)) {
  idx[[i]] <- any(sapply(MyList[-seq_len(i)], function(x) all(MyList[[i]] %in% x)))
}
# subset the list
MyList[!unlist(idx)]        
#$C
#[1] 6 7 8 9
#
#$A
#[1] 1 2 3 4 5
点赞