[R] Creating a list of all objects

Henrik Bengtsson hb at biostat.ucsf.edu
Tue Mar 29 23:55:52 CEST 2011


Return as.list(environment()), e.g.

foo <- function(x=1) {
  a <- 1;
  b <- 2;
  as.list(environment());
}

> foo()
$b
[1] 2
$a
[1] 1
$x
[1] 1

> a <- 2
> foo(x=2)
$b
[1] 2
$a
[1] 1
$x
[1] 2

> foo(x=4)
$b
[1] 2
$a
[1] 1
$x
[1] 4

See help("environment") for more information.

/Henrik

On Tue, Mar 29, 2011 at 2:37 PM, Sam Brown <s_d_j_brown at hotmail.com> wrote:
>
>
>
>
> Dear all
>
> I am trying to create a list of all objects created over the course of a function. To wit:
>
> foo <- function(x){
>    first <- x*(1:8)
>    second <- matrix(x*(1:16), ncol = 4)
>    third <- 1:x
>    list(x=x, first=first, second=second, third=third)
> }
>
> foo(5)
>
> No worries there. However, in the search for typing efficiency I wondered if it would be possible to use list(ls()) in the final line of the function. Unfortunately, this doesn't work. dump(ls(), file="") almost produces what I want, but not as a list. Are there any suggestions how I can create a list of all objects without manually declaring each object?
>
> Thanks for any insight!
>
> Sam
>
>
>
> Samuel Brown
> Casual research assistant
> Bio-Protection Research Centre
> PO Box 84
> Lincoln University
> Lincoln 7647
> Canterbury
> New Zealand
> sam.brown at lincoln.ac.nz
> http://www.the-praise-of-insects.blogspot.com
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list