user7988855
user7988855

Reputation: 115

Lists in R: What is actually happening?

I can't figure out why R behaves the following manner.

integerList <- list(1:10)
integerList[[1]] # this works
integerList[[1:2]] # this works BUT WHY?
integerList[[1:3]] # this fails, as I would expect

Why does integerList[[1:2]] work (I think it should fail), but integerList[[1:3]] fails (as I think it should). When the last line of code fails, the error message is:

Error in integerList[[1:3]] : recursive indexing failed at level 2

Why? Help!

Upvotes: 4

Views: 83

Answers (3)

Maurits Evers
Maurits Evers

Reputation: 50738

In integerList[[1:2]] you are asking for the second element of the list that is nested within the first element of integerList. A vector is just a special list in R, so this returns the second element, which is 2.

In integerList[[1:3]] you are asking for the third element of the second element of the list that is nested within the first element of integerList. This element clearly doesn't exist, hence the error.


To further demonstrate, two more examples:

Example 1

integerList[[c(1, 3)]]
#[1] 3

Here we are accessing the 3rd element of the first element of integerList.

Example 2

integerList2 <- list(list(1:10, 11:20))
integerList2
#[[1]]
#[[1]][[1]]
# [1]  1  2  3  4  5  6  7  8  9 10
#
#[[1]][[2]]
# [1] 11 12 13 14 15 16 17 18 19 20

integerList2[[1:3]]
#[1] 13

Here we are accessing the third element of the second element of the first element of integerList2.

Upvotes: 1

Henry
Henry

Reputation: 6784

integerList[[1:2]] is the same as integerList[[1]][[2]] i.e. the second element of the first element of integerList

integerList[[1:3]] is the same as integerList[[1]][[2]][[3]] i.e. the third element of the second element of the first element of integerList

Try

integerListoflists <- list(list(111:119,121:125),201:207)
integerListoflists[[1]][[2]][[3]]
integerListoflists[[1:3]]

to get both times

[1] 123

while both of

integerListoflists[[1]][[2]]
integerListoflists[[1:2]]

give

[1] 121 122 123 124 125

Upvotes: 0

Calum You
Calum You

Reputation: 15072

The comment by 李哲源 says this:

[[ can be applied recursively to lists, so that if the single index i is a vector of length p, alist[[i]] is equivalent to alist[[i1]]...[[ip]] providing all but the final indexing results in a list.

which is taken from the help page of [[. Try ?`[[` and look down the page.

What this means is that integerList[[1:2]] is equivalent to integerList[[1]][[2]], which returns 2 (since it is the second element of the vector in the first element of the list). Obviously 2 has no third element, so integerList[[1:3]] (which is integerList[[1]][[2]][[3]]) fails.

Upvotes: 2

Related Questions