3

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?

coletl
  • 803
  • 5
  • 17

1 Answers1

0

When you access a list through [1] or ["i"] you are still working on lists. If you access through [[1]] you are retrieving the value inside the first element of the list.

l=vector("list",10)
class(l["i"])
[1] "list"
class(l[1])
[1] "list"
class(l[[1]])
[1] "NULL"

If we were to test with a list containing a number:

l[[1]]=1
class(l[[1]])
[1] "numeric"

Summing up, with the first two operators you display what the list holds in that specific place. With the [[]] you display the thing itself.

boski
  • 2,437
  • 1
  • 14
  • 30