1

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 Answers3

0

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)
Arun
  • 116,683
  • 26
  • 284
  • 387
0

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.

Nishanth
  • 6,932
  • 5
  • 26
  • 38
  • It's not -0. It's -logical(0) = numeric(0) (vector of length 0), different from -0. – Arun Apr 10 '13 at 09:02
  • Right, but thats really splitting hair in this case. Result of `(1:5)[0]` is same as `(1:5)[someEmptyVector]`. Thats how R treats it internally for array indexing. – Nishanth Apr 10 '13 at 09:15
0

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.

Lorcan Treanor
  • 561
  • 1
  • 7
  • 19