【问题标题】:How to subtract two vectors' elements one by one?如何将两个向量的元素一一相减?
【发布时间】:2014-11-09 19:49:52
【问题描述】:

我有这两个向量:

first<-c(1,2,2,2,3,3,4)
second<-c(1,2)

现在我希望 first 没有 second 元素得到这样的结果:(2,2,3,3,4);确实, 我不希望所有2s 都被删除,只想一一减去。

我试过这个(来自here):

'%nin%' <- Negate('%in%')
first<-first[first %nin% second]

但它会从first 中删除所有2s 并给出以下结果:(3,3,4)

我该怎么做?

【问题讨论】:

  • @rawr 只是第一个!正如我所说,一个一个; first[-second]会一一做吗?
  • 我很困惑 second 是否应该是您要删除的 first 的索引,或者应该删除 first 中的特定元素模式。
  • @rawr 更通用的例子:让first 成为(1,2,4,2,3,1,2,3)second 成为(9,2,2,1)。在这种情况下,交叉点是(2,2,3)。所以应该从first 中删除两个 2 和一个 3。

标签: r vector


【解决方案1】:

试试这个:

first[-sapply(second, function(x) head(which(is.element(el=first, x)), 1))]
## [1] 2 2 3 3 4

如果您在 second 中有重复的元素,这将不起作用。在这种情况下,我认为你需要一个循环:

first2 <- first
for(i in seq_along(second)) {
    first2 <- first2[-head(which(is.element(el=first2, second[i])), 1)]
}
first2
# [1] 2 2 3 3 4

first2 <- first
second <- c(1,2,2)
for(i in seq_along(second)) {
    first2 <- first2[-head(which(is.element(el=first2, second[i])), 1)]
}
first2
## [1] 2 3 3 4

【讨论】:

  • 谢谢,我试试;但是first[-second] 可以安全地用于一一减法吗?
  • @majidgeek 试试rev(first)[-second],你会发现它不是。
【解决方案2】:

怎么样

second<-c(1, 2)
first[-match(second, first)]
## [1] 2 2 3 3 4

对于更复杂的情况,这里有一个使用&lt;&lt;-的选项

second <- c(1, 2, 2)
invisible(lapply(second, function(x) first <<- first[-match(x, first)]))
first
## [1] 2 3 3 4

【讨论】:

  • 这与我的第一个解决方案具有相同的限制。
  • @Thomas,我明白了。它仍然没有使用sapply 循环和其他一些不必要的功能:) 我会努力改进
  • 是的,这比我的第一个解决方案要好得多。
猜你喜欢
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多