访问/分配给出错误的父环境变量的函数

时间:2015-07-07 15:41:10

标签: r function scope environment local-variables

我尝试使用此功能

chan <- function(x) {
  for (i in x)
  {assign(i,sample(1:10,2))} 
  out <- data.frame(sapply(x,get))
  out
}

其中x将是字符串名称列表,此函数将为每个变量名称分配2个随机数,并将其作为数据框返回。

例如

 x <- c("e","f")

当我使用此功能时,它会出错 Error in FUN(..., ) : object ... not found

但如果我不使用该功能,只需运行循环即可。如:

x <- c("e","f")
for (i in x)
 {assign(i,sample(1:10,1))}
 out <- data.frame(sapply(x,get))

我想知道这里有什么不对。

1 个答案:

答案 0 :(得分:1)

您可以告诉assignget使用pos分配/获取变量时要使用的环境(此后x将位于您的全局环境中)

chan <- function(x) {
    for (i in x) {assign(i,sample(1:10,2), pos=1)}
    out <- data.frame(sapply(x, get, pos=1))
    out
}

或仅在本地功能环境中分配

chan <- function(x) {
    e <- environment()
    for (i in x) {
        assign(i,sample(1:10,2), pos=e)
    }
    out <- data.frame(sapply(x, get, pos=e))
    out
}