1

If I have a vector like this:

x <- c(1:10)

and I under-index it, by asking for position 0 like this:

x[0]

I get a return type of integer(0) which I understand to be a zero length integer vector. That is fine. However, if I ask for an invalid index that is too high like this:

x[11]

The return is NA.

So my question is, why the difference? Why not get a zero length vector in both cases or an NA in both cases? Is there a reason or is this just a quirk of R?

Steve Rowe
  • 19,411
  • 9
  • 51
  • 82
  • Don't know if you have already seen this, some useful answers https://stackoverflow.com/questions/3135325/why-do-vector-indices-in-r-start-with-1-instead-of-0 – Laksitha Ranasingha Feb 27 '19 at 22:30
  • 4
    [Here the question has been asked already with some answers](https://stackoverflow.com/questions/10610775/why-does-x0-return-a-zero-length-vector) – Croote Feb 27 '19 at 22:30
  • I can only construct a rationale for *both* behaviors in the context of negative indexes dropping elements: negative values greater than a vector's length do nothing (drop an element that isn't there), positive values greater than a vector's length return NA (select an unknown element, but this one is debatable as to how reasonable it is) and 0's do nothing. – joran Feb 27 '19 at 22:35
  • 1
    ...but really this mostly feels like a "quirk" in the sense that the behavior evolved organically over a series of decisions each of which had to fit with the previous ones. – joran Feb 27 '19 at 22:37
  • Thanks Croote. I looked for dupes and didn't run across that one. – Steve Rowe Feb 27 '19 at 23:09

0 Answers0