user321627
user321627

Reputation: 2592

In R, why does subsetting a negative numeric value of length 1 result in widely different results depending on what you subset it on?

In R, I saw that if we subset a negative number by negative values, we get -1. If somehow a 1 is placed in, we get numeric(0), and if positive numbers are the indices, we get NA's. Why is this?

> V <- -1
> V[-c(3,4)]
  [1] -1
> V[-c(1,3,4)]
  numeric(0)
> V[c(1,3,4)]
  [1] -1 NA NA

Upvotes: 0

Views: 30

Answers (1)

akrun
akrun

Reputation: 887971

In the second an third case, the actual index was present, and it results in removing that element to results in numeric(0) for the second case and in third with positive index, third and fourth doesn't exist and gives NA

c(1, 4, 3)[c(5, 6)] # // it is vector of length 3, so 5th and 6th doesn't exist
#[1] NA NA

c(1, 4, 3)[-c(5, 6)] # // no values in 5th and 6th to remove
#[1] 1 4 3    # // so it returns the original vector

In the OP's case

V[-1] # // returns numeric(0) as the first and only element is removed
#numeric(0)

Upvotes: 1

Related Questions