With single brackets, an index greater than a list's length returns a list containing a single element: NULL
.
Indexing with a non-existent name returns the same.
x <- as.list(1:10)
x[11]
# [[1]]
# NULL
x["i"]
# [[1]]
# NULL
I would expect indexing with [[
to return the value NULL
, as both x[["i"]]
and x$i
do.
However, [[
-indexing using a numeric value beyond the length of a list returns an error.
x[["i"]]
# NULL
x$i
# NULL
x[[11]]
# Error in x[[11]] : subscript out of bounds
What is the reason for the difference here? Why throw an error for just this one case, and not when a string index fails to match to an element name?
Difference from existing questions
To clarify, I am not asking when to use [
vs. [[
vs. $
. I understand that [[
and $
can be used for accessing the contents of only a single list element. I am wondering why a numeric index greater than the length of a list fails with an error for [[
only.
Phrased differently: if x[[11]]
uses a "subscript out of bounds", how come x[11]
is not doing the same?
I do not see this question as a duplicate. While this question discusses the same operators, none of the answers I've read directly address the NULL
and error difference I'm asking about.
Established inconsistency
Looking at section 4.3.3 in Advanced R, I see that this inconsistent behavior is actually well-known. The functions pluck()
and chuck()
from purrr
were invented for exactly this reason. Still, I wonder if anyone can provide some reasoning behind why R would be programmed this way?