Array of lists in r

Suppose if I want to have 10 arrays of elements, each element is a list / map. I'm doing it:

x = array(list(), 10) x[1][[ "a" ]] = 1 Warning message: In x[1][["a"]] = 1 : number of items to replace is not a multiple of replacement length > 

Is this the right approach? I want each element of the array to be a map.

+4
source share
2 answers

What you call an "array" is usually just called a list in R. You fall under the difference between [ and [[ for lists. See the section "Recursive (list-like) objects" in help("[") .

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

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

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

will not work because you cannot assign multiple values ​​to one element of the vector. If you want 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 
+5
source

If you really want to do this, since the list items in each element of the array have no names, you cannot index the character vector. In your example, there is no x[1][[ "a" ]] :

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

If there are no names, you need to index the numeric value:

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

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

 > y <- vector(mode = "list", length = 10) > y [[1]] NULL [[2]] NULL [[3]] NULL [[4]] NULL [[5]] NULL .... 
+5
source

All Articles