Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does `x[0]` return a zero-length vector?

Tags:

arrays

r

Say I have a vector, for example, x <- 1:10, then x[0] returns a zero-length vector of the same class as x, here integer(0).

I was wondering if there is a reason behind that choice, as opposed to throwing an error, or returning NA as x[11] would? Also, if you can think of a situation where having x[0] return integer(0) is useful, thank you for including it in your answer.

like image 211
flodel Avatar asked May 16 '12 01:05

flodel


3 Answers

As seen in ?"["

NA and zero values are allowed: rows of an index matrix containing a zero are ignored, whereas rows containing an NA produce an NA in the result.

So an index of 0 just gets ignored. We can see this in the following

x <- 1:10
x[c(1, 3, 0, 5, 0)]
#[1] 1 3 5

So if the only index we give it is 0 then the appropriate response is to return an empty vector.

like image 157
Dason Avatar answered Nov 01 '22 07:11

Dason


My crack at it as I am not a programmer and certainly do not contribute to R source. I think it may be because you need some sort of place holder to state that something occurred here but nothing was returned. This becomes more apparent with things like tables and split. For instance when you make a table of values and say there are zero of that cell you need to hold that that cell made from a string in a vector has no values. it would not be a appropriate to have x[0]==0 as it's not the numeric value of zero but the absence of any value.

So in the following splits we need a place holder and integer(0) holds the place of no values returned which is not the same as 0. Notice for the second one it returns numeric(0) which is still a place holder stating it was numeric place holder.

with(mtcars, split(as.integer(gear), list(cyl, am, carb)))
with(mtcars, split(gear, list(cyl, am, carb)))

So in a way my x[FALSE] retort is true in that it holds the place of the non existent zero spot in the vector.

All right this balonga I just spewed is true until someone disputes it and tears it down.

PS page 19 of this guide (LINK) state that integer() and integer(0) are empty integer.

Related SO post: How to catch integer(0)?

like image 41
Tyler Rinker Avatar answered Nov 01 '22 07:11

Tyler Rinker


Since the array indices are 1-based, index 0 has no meaning. The value is ignored as a vector index.

like image 21
Matthew Lundberg Avatar answered Nov 01 '22 07:11

Matthew Lundberg