[R] Filling Lists or Arrays of variable dimensions

Jessica Streicher j.streicher at micromata.de
Thu Dec 20 13:46:24 CET 2012


Following problem:

Say you have a bunch of parameters and want to produce results for all combinations of those:

height<-c("high","low")
width<-c("slim","wide")

then what i used to do was something like this:

l<-list()
for(h in height){
	l[[h]]<-list()
	for(w in width){
		l[[h]][[w]] <- doSomething()
	}
}

Now those parameters aren't always the same. Their number can change and the number of entries can change, and i'd like to have one code that can handle all configurations.

Now i thought i could use expand.grid() to get all configurations ,and than iterate over the rows, but the problem then is that i cannot set the values in the list like above.

grid<-expand.grid(height,width)
l[[as.character(grid[1,])]] <-1
Error in `[[<-`(`*tmp*`, as.character(grid[1, ]), value = 1) : 
  no such index at level 1

 This will only work if the "path" for that is already existent, and i'm not sure how to build that in this scenario. 

I then went on and built an array instead lists of lists, but that doesn't help either because i can't access the array with what i have in the grids row - or at least i don't know how.

Any ideas?

I'd prefer to keep the named lists since all other code is built towards this.


More information about the R-help mailing list