在环境中变换省略号

时间:2016-12-01 13:50:10

标签: r list

我有一个函数,参数是列表。如何访问参数并将其保存在环境中?也就是说,每个参数都是环境的一个要素。例如:

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]]

但我想在一个环境中保存参数。

1 个答案:

答案 0 :(得分:1)

这将返回一个环境,该参数使用参数作为未指定名称的任何参数的名称:

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 <- character(length(L))  # vector of "" elements
  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"   

上面的内容实际上有点乱,人们不会指望变量会自动命名。只要求调用者指定名称就更简单了:

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

注意:问题中的第一行代码(即a1 <- a2 <- a3 <- list())无效,因为在接下来的3行中会覆盖3个变量。