首页 > 解决方案 > 删除基本 R 中列表的第 i+1 个向量中的公共元素

问题描述

我想知道如果我可以找到并删除i+1列表的 -th 向量中的公共元素(在 base 中R)?

例如:

x = list(a = 1:5, b = 3:7, c = 6:9)      # Initial list
common <- # your solution                # ? find common values

 for(i in 1:length(x)) {

  # your solution: ?create `b` removing common elements with `a`
  # your solution: ?create `c` removing common elements with `b`
}

标签: rlistfunctionfor-loop

解决方案


当我们比较相邻元素时,使用setdiffwithlistlast元素first删除并更新'x'list

x[-1] <- Map(setdiff, x[-1], x[-length(x)])

推荐阅读