Wagner Jorge Wagner Jorge - 8 days ago 8
R Question

Transform ellipsis in environment

I have a function and the arguments are lists. How to access the arguments and save its in environment? That is, each argument is an element of environment. For example:

a1 <- a2 <- a3 <- list()
a1 <- matrix(rnorm(6), ncol = 2)
a2 <- matrix(rnorm(6), ncol = 2)
a3 <- matrix(rnorm(6), ncol = 2)

#I know to access the `...` and save its in list, but I don't want to save in list.
f <- function(...){
temp <- list(...)
temp
}

tt <- f(a1, a2, a3) #return a list of list
#To access the argument one
tt[[1]]


But I want to save the arguments in a environment.

Answer

This returns an environment using the arguments as the names if no names are specified.

set.seed(123)
a1 <- matrix(rnorm(6), ncol = 2)
a2 <- matrix(rnorm(6), ncol = 2)
a3 <- matrix(rnorm(6), ncol = 2)

f2 <- function(...) {
  L <- list(...)
  nms <- names(L)
  if (is.null(nms)) nms <- rep("", length(L))
  names(L) <- ifelse(nms == "", as.character(match.call()[-1]), nms)
  list2env(L)
}

e <- f2(a1, a2, a3)
ls(e)
## [1] "a1" "a2" "a3"

e <- f2(2 * a1, X = a2, a3)
ls(e)
## [1] "2 * a1" "a3"     "X"   

The above is really a bit messy and one would not expect that variables are automatically named. It would be simpler to just require that the caller specify the names:

f3 <- function(...) list2env(list(...))
e <- f3(a1 = a1, a2 = a2, a3 = a3)
ls(e)
## [1] "a1" "a2" "a3"

Note: The first line of code in the question, i.e. a1 <- a2 <- a3 <- list(), has no effect since the 3 variables are overwritten in the next 3 lines.