1

Similar to this question:

Return elements of list as independent objects in global environment

I cannot seem to adapt the answer to assign the list elements when list2env is called inside a function:

E.g.

lst <- list(a = c(1, 2), b = c(3, 4))

tmp_fn <- function(lst) {
    # do computations on list elements
    # first assign each to the function environment
    list2env(lst, parent = parent.frame()) # fails

    # do stuff
    ...
}

I thought the parent = parent.frame() would work, but while debugging tmp_fn I only see that lst gets assigned to the function environment as a list, not the individual variables a and b.

Community
  • 1
  • 1
Alex
  • 15,186
  • 15
  • 73
  • 127
  • Perhaps you just want to `attach(lst)` in your function? The `pos` argument might be friendlier to work with, and the default `2L` I think does what you want. – Gregor Thomas Nov 16 '16 at 01:55
  • I thought that `attach` is not recommended? – Alex Nov 16 '16 at 01:59
  • `attach` isn't recommend, but you're trying to do what `attach` does. The general recommendation would be to use your `list` as you have it. – Gregor Thomas Nov 16 '16 at 02:02

1 Answers1

2

1) Use envir= here rather than parent= like this. Also, as shown, you may wish to add envir as an argument for flexibility:

lst <- list(a = c(1, 2), b = c(3, 4))

tmp_fn <- function(lst, envir = parent.frame()) {
    invisible(list2env(lst, envir = envir))
}
tmp_fn(lst)

2) Another possibility is to use list[...]<- from the gsubfn package (development version):

devtools::install_github("ggrothendieck/gsubfn")
library(gsubfn)

func <- function(lst) lst
list[a, b] <- func(lst)

Now a and b will be in the current environment.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • I have tried your first solution, thanks. It seems like you may have slightly misinterpreted my question. I do not want a function `tmp_fn` that assigns the list objects into the calling environment of `tmp_fn`. Instead, I would like the elements to be assigned into the environment of `tmp_fn` when it is called. Your solution still works as I can do something like. `tmp_fn2 <- function(lst){tmp_fn1(lst)}`, which does assign the `lst` elements into the function environment of `tmp_fn2`. However, I wonder whether there is a more straightfoward way of doing this without defining another function. – Alex Nov 30 '16 at 06:05
  • You can specify `envir` to be whatever you want. For example, define the default value of envir as `envir=parent.env(environment())` instead of `envir=parent.frame()` – G. Grothendieck Nov 30 '16 at 15:25