array of lists in r

后端 未结 2 989
陌清茗
陌清茗 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
    

提交回复
热议问题