【问题标题】:Finding missing values between lists in R [duplicate]在R中的列表之间查找缺失值[重复]
【发布时间】:2016-10-27 19:02:08
【问题描述】:

我有两组列表,需要检查第一个列表中的每个向量与第二个列表中对应的向量,看看缺少什么(我只对第一个列表中没有的内容感兴趣第二个)。

样本数据:

> x <- list(c(100,5,1), c(1,20,5)) 
> y <- list(c(1,2,5,10,20,50,100), c(1,20,50,100))

我需要取消列出和使用 setdiff(),所以我使用一个函数来做这两个:

> lapply(x, function(a,b) setdiff(unlist(a),unlist(b)), y)

第一组的预期结果是什么,第二组的预期结果是 5。不幸的是,这并没有拾取 x[2] 中但不在 y[2] 中的 5。相反,这是我的结果:

[[1]]
numeric(0)

[[2]]
numeric(0)

奇怪的是,它似乎匹配 5 到 50(也许?),因为如果我将 x[2] 中的 5 更改为 y[2] 中找不到的 3 之类的数字,我会得到预期的结果结果:

> x <- list(c(100,5,1), c(1,20,3))
> lapply(x, function(a,b) setdiff(unlist(a),unlist(b)), y)
[[1]]
numeric(0)

[[2]]
[1] 3

知道发生了什么吗?或者有更好的方法吗?

【问题讨论】:

  • @Daniel 给了我一个很好的答案,但我仍然希望我能理解 setdiff 在我最初的尝试中发生了什么。
  • 添加几个print 语句来调试你的代码,你会看到它在做什么:lapply(x, function(a, b){ print(paste0("a: ", paste0(unlist(a), collapse = ", "))) print(paste0("b: ", paste0(unlist(b), collapse = ", "))) setdiff(unlist(a), unlist(b)) }, y)

标签: r set-difference


【解决方案1】:

这个怎么样?

lapply(seq_along(x), function(i) setdiff(x[[i]], y[[i]]))

【讨论】:

    猜你喜欢
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    相关资源
    最近更新 更多