空索引向量的补充再次是空索引向量

时间:2013-04-10 08:34:26

标签: r vector indexing complement

我知道这个问题已经发布,但答案是以其他方式解决给定问题的一个技巧,但核心问题仍然没有答案。

问题是这个。

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

为什么它不是原始载体?

是否有理由或者我理解错了。 如果是这样,那么获得索引向量的补码是否正确。

3 个答案:

答案 0 :(得分:0)

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)

答案 1 :(得分:0)

那是因为-0 = 0?但我可以看到如果这个方面被忽视,算法如何遇到问题。所以我建议使用setdiff而不是负指数。

答案 2 :(得分:0)

somevector&lt; - c(1:5,NA,8)
sumvec&LT; -subset(!somevector,is.na(somevector))

不太确定这是否是您想要的,但如果您想要不同的东西,请告诉我,以便我能够纠正我的答案。如果这是您正在寻找的答案,那么哈希标记的答案是另一种答案。