Reputation: 15708
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
.
Upvotes: 1
Views: 455
Reputation: 269644
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.
Upvotes: 2