Indexing nested list structure in R

前端 未结 1 1228
傲寒
傲寒 2021-01-15 15:04

I have transitioned from STATA to R, and I was experimenting with different data types so that R\'s data structures are clear in my mind.

Here\'s how I set up my dat

相关标签:
1条回答
  • 2021-01-15 15:28

    I think this is sufficient to answer your question. Consider a length-1 list:

    x <- list(u = 5)
    #$u
    #[1] 5
    length(x)
    #[1] 1
    
    x[1]
    x[1][1]
    x[1][1][1]
    ...
    

    always gives you the same:

    #$u
    #[1] 5
    

    In other words, x[1] will be identical to x, and you fall into infinite recursion. No matter how many [1] you write, you just get x itself.

    If I create t1<-list(u=5,v=7), and then do t1[2][1][1][1]...this works as well. However, t1[[2]][2] gives NA


    That is the difference between [[ and [ when indexing a list. Using [ will always end up with a list, while [[ will take out the content. Compare:

    z1 <- t1[2]
    ## this is a length-1 list
    #$v
    #[1] 7
    class(z1)
    # "list"
    
    z2 <- t1[[2]]
    ## this takes out the content; in this case, a vector
    #[1] 7
    class(z2)
    #[1] "numeric"
    

    When you do z1[1][1]..., as discussed above, you always end up with z1 itself. While if you do z2[2], you surely get an NA, because z2 has only one element, and you are asking for the 2nd element.


    Perhaps this post and my answer there is useful for you: Extract nested list elements using bracketed numbers and names?

    0 讨论(0)
提交回复
热议问题