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

Hans Ekbrand hans at sociologi.cjb.net
Tue Oct 5 02:27:55 CEST 2010


On Mon, Oct 04, 2010 at 10:07:06AM -0400, Gabor Grothendieck wrote:
> Some small tweaks.   If you use simplify=FALSE then it will guarantee
> that a list is returned:
> 
>    sapply(my.names, get, simplify = FALSE)
> 
> for example, compare the outputs of:
> 
>    sapply(c("letters", "LETTERS"), get)
>    sapply(c("letters", "LETTERS"), get, simplify = FALSE)

Thanks Gabor, 

But get() fails to find my objects, though get() successfully finds
"letters" and "LETTERS" (but they are part of the global environment,
I assume).

a <- c("not", "this")
b <- c(0,0)
my.test.function <-  function() {
  a <- 1:3
  b <- c("x", "y")
  sapply(c("a", "b"), get, simplify = FALSE)
}
my.test.function()
$a
[1] "not"  "this"

$b
[1] 0 0

rm(a,b)
my.test.function <-  function() {
  a <- 1:3
  b <- c("x", "y")
  sapply(c("a", "b"), get, simplify = FALSE)
}
my.test.function()

Error in FUN(c("a", "b")[[1L]], ...) : object 'a' not found

If get() is what should be used, then how do you get it to find
objects in the environment of the function? I would prefer to write a
special my.return() and for get() to work there, perhaps some deep R
magic is needed. Something like this is what I aim for:

my.return <- function(my.names) {
  sapply(my.names, get, simplify = FALSE)
}

my.function <- function() {
...
summarize data
...
my.return(summary.one, summary.two ...)
}


Kind regards, Hans
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: Digital signature
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20101005/3c0e5ee4/attachment.bin>


More information about the R-help mailing list