在局部变量上使用“ get”内部嵌套函数

The*_*Man 3 nested r function

我从来没有完全了解嵌套函数和通过引用传递参数。我的策略通常是在子函数get('variabletopassbyreference')内部执行类似操作。

到目前为止,我一直在将全局变量传递给该函数,并且此方法运行良好。今天,我尝试在一个函数内创建局部变量,然后将其传递给该函数内的嵌套函数,但失败了。我无法get上班。我也尝试修改pos和,inherits但无济于事。

我在网上找不到确切的答案。如果我可以使这种构造正常工作,那是我的偏爱,因为我还有很多其他功能都以类似的方式编写。如果我根本不应该这样做,而应该做其他事情,那么该信息也将不胜感激。

下面是一个示例-

test1 <- function(a1,b1) {

  # cat(ls()) # a1 b1
  # cat(ls(pos = 1)) # c test1 test2

  testvalue <- get('c') * get(a1, inherits = TRUE) * get(b1)

  testvalue

}

test2 <- function() {

  a = 1
  b <- 2
  # cat(ls()) # a b
  test1('a','b')

}

c = 3
test2()
Run Code Online (Sandbox Code Playgroud)

我收到以下错误-

Error in get(a1, inherits = TRUE) : object 'a' not found 
Run Code Online (Sandbox Code Playgroud)

更通用的示例-

a = 0

test1 <- function(a1,b1) {

  # cat(ls()) # a1 b1
  # cat(ls(pos = 1)) # c test1 test2

  testvalue <- get('c') * a1 * b1

  assign(x = 'a', value = 2.5)
  assign(x = 'a', value = 3.5, envir = parent.frame())
  assign(x = 'a', value = 4.5, envir = .GlobalEnv)
  cat(a)
  cat(' - value of a local within test1\n')
  testvalue

} 

test2 <- function() {

  a = 1
  b <- 2
  # cat(ls()) # a b

  cat(a)
  cat(' - value of a local within test2 before test1 called\n')
  test1(a1 = a, b1 = b)
  cat(a)
  cat(' - value of a local within test2 after test1 called\n')

}
cat(a)
cat(' - value of a global before test 2 \n')
c = 3
test2()

cat(a)
cat(' - value of a global after test 2 \n')
Run Code Online (Sandbox Code Playgroud)

G. *_*eck 5

另外,传递变量所在的环境。请注意,它parent.frame()指的是调用者当前正在运行的实例中的环境。

test1 <- function(a1, b1, env = parent.frame()) {

  a <- get(a1, env)
  b <- get(b1, env)
  c <- get('c', env)

  testvalue <- c * a * b

  testvalue

}

c <- 3
test2() # test2 as in question
## 6
Run Code Online (Sandbox Code Playgroud)

这里abenv c不在env,但它是一个祖先envget容貌通过ancenstors为好。

ADDED 注意的是,R的公式可以用于传递变量名与环境:

test1a <- function(formula) {
    v <- all.vars(formula)
    values <- sapply(v, get, environment(formula))
    prod(values)
}

test2a <- function() {
    a <- 1
    b <- 2
    test1a(~ a + b + c)
}

c <- 3
test2a()
## 6
Run Code Online (Sandbox Code Playgroud)

修订:已更正。添加了评论。添加了有关公式的信息。