[R] naming list elements

Michael Wolosin michael.wolosin at duke.edu
Mon Jan 31 20:58:25 CET 2005


All -

Each time through a loop I create a new dataset, which I would like to 
append to a list object.  Each item of the list should be the data matrix 
created in that step of the loop; I would like the NAME (or tag) of that 
list item to be assigned the value of a character string:

I've tried something like this:

running.list <- numeric(0)
for(i in 1:num.files){
.....
running.list <- append(running.list, list(this.item.name=newdatamatrix))
}

but the name of the item is always "this.item.name" instead of the CONTENTS 
of the character string called "this.item.name".

Obviously, this is correct from R's standpoint, but it's not what I want.

I can force it to do what I want by doing this:

running.list <- numeric(0)
for(i in 1:num.files){
.....
junk <- list(newdatamatrix)
names(junk) <- list(this.item.name)
running.list <- append(running.list, junk)
}

but this requires an extra assigment step, and so has two whole copies of 
the data matrix laying around.  (Some might point out that I'm being 
ridiculous worrying about memory if I create a list in this way, but that's 
another question...)

In some macro languages I've used, there are ways to force the evaluation 
of a section of code before it is passed on to the function call (in this 
case, I'd like to evaluate this.item.name and then effectively call the 
string "list(blah=newdatamatrix)")
I've tried doing exactly that, i.e.,
eval(paste("list(",this.item.name,"=newdatamatrix)"),sep="")

but that doesn't seem to work either.  It seems like I should be able to do 
this with eval, call, or something...

Thanks in advance for any help the list has to offer,

Mike




More information about the R-help mailing list