Subsetting list in R using double square brackets

懵懂的女人 提交于 2019-12-20 07:39:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!