【问题标题】:environments, sys.frame() and sys.nframe in R环境,R 中的 sys.frame() 和 sys.nframe
【发布时间】:2021-07-27 23:03:00
【问题描述】:

喂! 我正在玩R中的环境。 这是一个最小的例子:

test_function <- function() {
 list2env(list(test = 5), envir = sys.frame(sys.nframe()))
  test_function2()
}

test_function2 <- function() {
  #access variable test here
}

第 2 部分

test_function <- function() {
  print(sys.nframe())
  x <- 5
 list2env(list(test = x), envir = sys.frame(sys.nframe()))
  test_function2()
}

test_function2 <- function(envir = parent.frame()) {
  print(sys.nframe())
  x <- envir$test
  if (x<5) {
    test_function3()
  } else{
    test_function2()
  }

}
test_function3 <- function(envir = parent.frame()) {
  
}

在 test_function2() 的第二次调用中,我无法访问测试。

谁能告诉我如何访问 test_function2 中的变量 test? 提前致谢!

【问题讨论】:

    标签: r environment-variables


    【解决方案1】:

    使用来自问题的test_function,我们从父框架中检索test

    test_function2 <- function(envir = parent.frame()) {
        envir$test
    }
    
    test_function()
    ## [1] 5
    

    第 2 部分

    envir 需要传递下去。这就是为什么它在第一部分中提出了一个论点。我们修改了这个例子,去掉了无限递归。

    test_function <- function(x) {
      list2env(list(test = x), environment())
      test_function2(z = 5)
    }
    
    test_function2 <- function(z, envir = parent.frame()) {
      x <- envir$test
      if (x<z) test_function3(envir) else Recall(z+1, envir)
    }
    
    test_function3 <- function(envir = parent.frame()) {
      envir$test
    }
    
    trace(test_function)
    trace(test_function2)
    trace(test_function3)
    
    test_function(4)
    ## trace: test_function(4)
    ## trace: test_function2
    ## trace: test_function3
    ## [1] 4
    
    test_function(5)
    ## trace: test_function(5)
    ## trace: test_function2
    ## trace: test_function2
    ## trace: test_function3
    ## [1] 5
    

    【讨论】:

    • 如果我有很多功能并且 parent.frame() 始终不一样,那么方法如何?我的目标是列出环境变量并从每个“子”函数访问它们。
    • test_function2 应该适用于任何包含test 的调用者。 ls(envir) 将列出父级中的变量名称。
    • 我在主要问题中添加了我的问题。感谢您的帮助:)
    • 随着我想达到的无限入侵,我第二次调用 test_function2。因为那么 parent.frame() 就是 test_funtion2 的环境。还是我错了?
    • 好的。我已经对其进行了修改,以便 test_function2 调用自己一次。关键是,通过将envir 向下传递到一个参数,我们甚至可以从调用树深处调用的函数访问test_function 中的test
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    相关资源
    最近更新 更多