Skip to content
Prev 246274 / 398502 Next

Saving objects inside a list

What version of R are you using?  In 2.12.0 I get
  > x <- 1:7
  > y <- function(...)list(...)
  > z <- runif(3) # creates .Random.seed also
  > str(as.list(.GlobalEnv)) # add all.names=TRUE to get .Random.seed
  List of 3
   $ z: num [1:3] 0.698 0.475 0.354
   $ y:function (...)
    ..- attr(*, "source")= chr "function(...)list(...)"
   $ x: int [1:7] 1 2 3 4 5 6 7
  > str(eapply(.GlobalEnv, function(x)x)) # all.names=TRUE ok here also
  List of 3
   $ z: num [1:3] 0.698 0.475 0.354
   $ y:function (...)
    ..- attr(*, "source")= chr "function(...)list(...)"
   h$ x: int [1:7] 1 2 3 4 5 6 7
Use environment() instead of .GlobalEnv if you want to
process the current environment.

In any version of R sapply() can give incorrect results,
as in (in a fresh vanilla R session):
  > x <- 1:4
  > y <- 11:14
  > z <- 21:24
  > str(sapply(ls(), get))
   int [1:4, 1:3] 1 2 3 4 11 12 13 14 21 22 ...
   - attr(*, "dimnames")=List of 2
    ..$ : NULL
    ..$ : chr [1:3] "x" "y" "z"
or, in another fresh session
  > FUN <- "a string named FUN"
  > X <- 17
  > sapply(ls(), get)
  $FUN
  function (x, pos = -1, envir = as.environment(pos), mode = "any",
      inherits = TRUE)
  .Internal(get(x, envir, mode, inherits))
  
  $X
  [1] "FUN" "X"

as.list(envir) and eapply(envir, function(x)x) do
not have problems in those cases.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com