array of lists in r

后端 未结 2 959
陌清茗
陌清茗 2020-12-30 16:13

Suppose if I want to have 10 element array each element is a list/map. I am doing this:

x = array(list(), 10)
x[1][[ \"a\" ]] = 1
Warning message:
In x[1][[\         


        
相关标签:
2条回答
  • 2020-12-30 16:46

    What you're calling an "array" is usually just called a list in R. You're getting tripped up by the difference between [ and [[ for lists. See the section "Recursive (list-like) objects" in help("[").

    x[[1]][["a"]] <- 1
    

    UPDATE:
    Note that the solution above creates a list of named vectors. In other words, something like

    x[[1]][["a"]] <- 1
    x[[1]][["b"]] <- 1:2
    

    won't work because you can't assign multiple values to one element of a vector. If you want to be able to assign a vector to a name, you can use a list of lists.

    x[[1]] <- as.list(x[[1]])
    x[[1]][["b"]] <- 1:2
    
    0 讨论(0)
  • 2020-12-30 16:53

    If you really want to do this, then, because the elements of the lists in each element of the array do not have names, you can't index by a character vector. In your example, there is no x[1][[ "a" ]]:

    > x[1][[ "a" ]]
    NULL
    

    If there are no names then you need to index by a numeric:

    > x[1][[ 1 ]] <- 1
    [1] 1
    

    It would seem more logical to have a list though than an array:

    > y <- vector(mode = "list", length = 10)
    > y
    [[1]]
    NULL
    
    [[2]]
    NULL
    
    [[3]]
    NULL
    
    [[4]]
    NULL
    
    [[5]]
    NULL
    ....
    
    0 讨论(0)
提交回复
热议问题