[R] creating named elements of lists on the fly

Sundar Dorai-Raj sundar.dorai-raj at PDF.COM
Fri Oct 8 19:09:24 CEST 2004



Ben Shapiro wrote:

> HI Folks,
> 
> I'm trying to create a list with named elements. Only, I don't know the names of the elements a priori (they come from the data being calculated). Currently, my approach is to create an environment, then assign things to the environement, then as.list the environment to get a list. 
> 
> Running the code gives, for example:
> 
>>e2 <- new.env(FALSE, NULL)
>>assign("dude", 123, env=e2)
>>assign("chick", 456, env=e2)
>>as.list(e2)
> 
> Error in as.vector(x, "list") : cannot coerce to vector
> 
> Is this the best way to make a list like this? 
> 
> Thanks,
> Ben
> 

You can use the "[[" operator for list objects:

nm <- c("dude", "chick")
e2[[nm[1]]] <- 123
e2[[nm[2]]] <- 456

HTH,

--sundar




More information about the R-help mailing list