【问题标题】:Complement of empty index vector is empty index vector again空索引向量的补码又是空索引向量
【发布时间】:2013-04-10 08:34:25
【问题描述】:

我知道这个问题已经发布,但答案是通过其他方式解决给定问题的技巧,但核心问题仍未得到解答。

问题是这样的。

somevector <- 1:5
emptyindeces <- vector()
somevector[-emptyindeces] #returns empty vector

为什么不是原始向量?

这是有原因的还是我理解错了。 如果是这样,那么获取索引向量的补码的正确方法是什么。

【问题讨论】:

  • 能否提供您所指问题的链接?

标签: r vector indexing complement


【解决方案1】:

emptyindiceslogical(0)(长度 = 0 的逻辑向量),-emptyindices 变为 integer(0)。因此,您正在查询索引长度为 0 的向量。您得到一个长度 = 0 整数向量。

您可能正在寻找,例如setdiff

v <- 6:10
idx1 <- c(1,3)
idx2 <- vector()
idx3 <- 1:5

v[setdiff(seq_along(v), idx1)]
# [1] 7 9 10

v[setdiff(seq_along(v), idx2)]
# [1] 6 7 8 9 10

v[setdiff(seq_along(v), idx3)]
# integer(0)

【讨论】:

    【解决方案2】:

    那是因为-0 = 0?但是我可以看到如果忽略这一方面,算法会如何遇到问题。所以我建议使用setdiff 而不是负索引。

    【讨论】:

    • 不是-0。它是 -logical(0) = numeric(0)(长度为 0 的向量),与 -0 不同。
    • 是的,但在这种情况下,这真的很分裂。 (1:5)[0] 的结果与 (1:5)[someEmptyVector] 相同。这就是 R 在内部处理数组索引的方式。
    【解决方案3】:

    somevector sumvec

    不太确定这是否是您想要的,但如果您想要不同的东西,请告诉我,以便我更正我的答案。如果这是您正在寻找的答案,则带有标签的答案是替代答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      • 2021-10-01
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多