问题
After reading several threads about subsetting lists in R, I tried to fully grasp this notion by fooling around in Rstudio. I thought I understood the concept until I came across the following:
x <- list(list(list(1), 2), list(list(list(3), 4), 5), 6)
Why is it that x[[1]]
returns a list with two elements and x[[1]][[1]]
returns a list too?
回答1:
Well, if you just write the definition of the list like this -
x <- list(
list(
list(1),
2
),
list(
list(
list(3),
4
),
5
),
6
)
then it is easy to see that x[[1]]
is
[[1]]
[[1]][[1]]
[1] 1
[[2]]
[1] 2
So x[[1]]
comprises two elements - a list of one element 1, and the vector 2. x[[1]][[1]]
extract the list of one element.
回答2:
Look at the code with two extra spaces to help make the structure more clear:
x <- list( list( list(1), 2), list(list(list(3), 4), 5), 6)
The first element of x is: list( list(1), 2)
# clearly a list with two elements
And the first element of that list is: list(1)
# also a list but with one element
回答3:
Single brackets do subsetting. Double brackets do extraction.
So x[1]
is a single element list (x
reduced to only its first element).
But you did x[[1]]
, which extracts the first element from x
, and it was a two element list as others explained.
x[[1]][[1]]
extracts the first element from the first element of x
.
来源:https://stackoverflow.com/questions/51293799/subsetting-list-in-r-using-double-square-brackets