Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multi-dimensional list? List of lists? array of lists?

(I am definitively using wrong terminology in this question, sorry for that - I just don't know the correct way to describe this in R terms...)

I want to create a structure of heterogeneous objects. The dimensions are not necessary rectangular. What I need would be probably called just "array of objects" in other languages like C. By 'object' I mean a structure consisting of different members, i.e. just a list in R - for example:

myObject <- list(title="Uninitialized title", xValues=rep(NA,50), yValues=rep(NA,50)) 

and now I would like to make 100 such objects, and to be able to address their members by something like

for (i in 1:100) {myObject[i]["xValues"]<-rnorm(50)}

or

for (i in 1:100) {myObject[i]$xValues<-rnorm(50)}

I would be grateful for any hint about where this thing is described.

Thanks in advance!

like image 804
Vasily A Avatar asked Feb 23 '13 23:02

Vasily A


2 Answers

are you looking for the name of this mythical beast or just how to do it? :) i could be wrong, but i think you'd just call it a list of lists.. for example:

# create one list object
x <- list( a = 1:3 , b = c( T , F ) , d = mtcars )

# create a second list object
y <- list( a = c( 'hi', 'hello' ) , b = c( T , F ) , d = matrix( 1:4 , 2 , 2 ) )

# store both in a third object
z <- list( x , y )

# access x
z[[ 1 ]] 

# access y
z[[ 2 ]]

# access x's 2nd object
z[[ 1 ]][[ 2 ]]
like image 106
Anthony Damico Avatar answered Nov 16 '22 00:11

Anthony Damico


I did not realize that you were looking for creating other objects of same structure. You are looking for replicate.

my_fun <- function() {
    list(x=rnorm(1), y=rnorm(1), z="bla")
}
replicate(2, my_fun(), simplify=FALSE)

# [[1]]
# [[1]]$x
# [1] 0.3561663
# 
# [[1]]$y
# [1] 0.4795171
# 
# [[1]]$z
# [1] "bla"
# 
# 
# [[2]]
# [[2]]$x
# [1] 0.3385942
# 
# [[2]]$y
# [1] -2.465932
# 
# [[2]]$z
# [1] "bla"
like image 45
Arun Avatar answered Nov 16 '22 00:11

Arun