Complement of empty index vector is empty index ve

2019-03-01 18:11发布

I know this question was already posted but the answer was a trick to solve the given problem some other way, but the core question remained unanswered.

The question is this.

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

Why it is not the original vector?

Is there a reason for that or am I understanding it wrong. If so whats the correct way to get the complement of an index vector.

3条回答
Animai°情兽
2楼-- · 2019-03-01 18:20

somevector <- c(1:5,NA,8)
sumvec<-subset(somevector,!is.na(somevector))

Not too sure if this is what you want, but let me know if you wanted something different so I can correct my answer. The answer hashtagged is an alternative answer if this is what you were looking for.

查看更多
迷人小祖宗
3楼-- · 2019-03-01 18:23

emptyindices is logical(0) (logical vector of length = 0) and -emptyindices becomes integer(0). So, you're querying the vector with indices of length = 0. You get back a length = 0 integer vector.

Probably you are looking for, for example, 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)
查看更多
Melony?
4楼-- · 2019-03-01 18:28

Thats because -0 = 0? But I can see how an algorithm can run into problem if this aspect is over-looked. So I suggest using setdiff instead of negative indices.

查看更多
登录 后发表回答