[Rd] Shouldn't vector indexing with negative out-of-range index give an error?

Henrik Bengtsson henrik.bengtsson at ucsf.edu
Mon May 4 21:20:44 CEST 2015


In Section 'Indexing by vectors' of 'R Language Definition'
(http://cran.r-project.org/doc/manuals/r-release/R-lang.html#Indexing-by-vectors)
it says:

"Integer. All elements of i must have the same sign. If they are
positive, the elements of x with those index numbers are selected. If
i contains negative elements, all elements except those indicated are
selected.

If i is positive and exceeds length(x) then the corresponding
selection is NA. A negative out of bounds value for i causes an error.

A special case 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."

However, that "A negative out of bounds value for i causes an error"
in the second paragraph does not seem to apply.  Instead, R silently
ignore negative indices that are out of range.  For example:

> x <- 1:4
> x[-9L]
[1] 1 2 3 4
> x[-c(1:9)]
integer(0)
> x[-c(3:9)]
[1] 1 2

> y <- as.list(1:4)
> y[-c(1:9)]
list()

Is the observed non-error the correct behavior and therefore the
documentation is incorrect, or is it vice verse?  (...or is it me
missing something)

I get the above on R devel, R 3.2.0, and as far back as R 2.11.0
(haven't check earlier versions).

Thank you,

Henrik



More information about the R-devel mailing list