Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array of lists in r

Tags:

arrays

r

map

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][["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.

like image 309
user236215 Avatar asked Apr 18 '11 16:04

user236215


People also ask

Can you have lists of lists in R?

The list is one of the most versatile data types in R thanks to its ability to accommodate heterogenous elements. A single list can contain multiple elements, regardless of their types or whether these elements contain further nested data. So you can have a list of a list of a list of a list of a list …

How do I turn a list into a array in R?

A list can be converted to array in R by calling unlist( ) function with created list as parameter. Now pass the unlist() function into array() function as parameter, and use dim attribute for specifying number of rows, columns and matrices. unlist() converts list to vector.

Can you have a vector of lists in R?

Almost all data in R is stored in a vector, or even a vector of vectors. A list is a recursive vector: a vector that can contain another vector or list in each of its elements. Lists are one of the most flexible data structures in R.

What is list of lists in R?

The list can be a list of vectors, a list of matrices, a list of characters and a list of functions, and so on. A list is a vector but with heterogeneous data elements. A list in R is created with the use of list() function. R allows accessing elements of a list with the use of the index value.


2 Answers

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
like image 78
Joshua Ulrich Avatar answered Sep 28 '22 01:09

Joshua Ulrich


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
....
like image 34
Gavin Simpson Avatar answered Sep 28 '22 03:09

Gavin Simpson