[R] how to make list() return a list of *named* elements

Berwin A Turlach berwin at maths.uwa.edu.au
Mon Oct 4 13:45:23 CEST 2010


G'day Hans,

On Mon, 4 Oct 2010 11:28:15 +0200
Hans Ekbrand <hans at sociologi.cjb.net> wrote:

> On Thu, Sep 30, 2010 at 09:34:26AM -0300, Henrique Dallazuanna wrote:
> > You should try:
> > 
> > eapply(.GlobalEnv, I)[c('b', 'my.c')]
> 
> Great!
> 
> b <- c(22.4, 12.2, 10.9, 8.5, 9.2)
> my.c <- sample.int(round(2*mean(b)), 4)
> 
> my.return <- function (vector.of.variable.names) {
>   eapply(.GlobalEnv, I)[vector.of.variable.names]
> }

Well, if you are willing to create a vector with the variable names,
then simpler solutions should be possible, i.e. solutions that only
operate on the objects of interest and not on all objects in the global
environment (which could be a lot depending on your style).  For
example:

R> my.return <- function (vector.of.variable.names) {
  sapply(vector.of.variable.names, function(x) list(get(x)))
}
R> str(my.return(c("b","my.c")))
List of 2
 $ b   : num [1:5] 22.4 12.2 10.9 8.5 9.2
 $ my.c: int [1:4] 7 5 23 4

Cheers,

	Berwin

========================== Full address ============================
Berwin A Turlach                      Tel.: +61 (8) 6488 3338 (secr)
School of Maths and Stats (M019)            +61 (8) 6488 3383 (self)
The University of Western Australia   FAX : +61 (8) 6488 1028
35 Stirling Highway                   
Crawley WA 6009                e-mail: berwin at maths.uwa.edu.au
Australia                        http://www.maths.uwa.edu.au/~berwin



More information about the R-help mailing list