Why does the matrix type in R allow for indexing with zero if indexing starts from 1 ?
> m = diag(10)
> dim(m[0,0])
[1] 0 0
Is this a bug in the language implementation or a feature ?
Why does the matrix type in R allow for indexing with zero if indexing starts from 1 ?
> m = diag(10)
> dim(m[0,0])
[1] 0 0
Is this a bug in the language implementation or a feature ?
It's certainly intentional. From the relevant section of the R Language Definition:
All elements of
i[an integer vector of indices] must have the same sign. If they are positive, the elements ofxwith those index numbers are selected. Ificontains negative elements, all elements except those indicated are selected.
...
A special case [of using integers to index a vector] is the zero index, which has null effects:
x[0]is an empty vector and otherwise including zeros among positive or negative indices has the same effect as if they were omitted.
You can argue about whether this is a good idea or not (should including a zero in an integer vector of indices throw an error? Return NA? Something else?), but that will rapidly descend into opinion-based territory.