访问传递给父R函数或在父R函数中定义的变量 [英] Accessing variables passed to, or defined in, parent R function

查看:49
本文介绍了访问传递给父R函数或在父R函数中定义的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果未在函数范围内定义变量,则称R在父环境中查找该变量,然后在该环境的父目录中寻找该变量,依此类推.

If a variable is not defined in the scope of a function, R is said to look in for the variable in the parent environment, then the parent of that environment, and so forth.

似乎不是将变量传递给函数的情况:

This does not seem to be the case where variables are passed to functions:

Foo <- function (y) {
  message('In Foo, x = ', x)
}

Func1 <- function (x = 1) {
  message('In Func1, x = ', x)
  Foo(1)
  lapply(1:2, Foo)
}

Func2 <- function () {
  x <- 2
  message('In Func2, x = ', x)
  Foo(1)
}

Func1(x = 1) # Foo throws error
Func2() # Foo throws error
x <- 99 
Func2() # Now Foo uses value of x from global environment


remove(x)

如何启用功能 Foo 来在父函数及其父项中搜索变量的值,而不是在全局环境中使用该值?

How do I enable the function Foo to search the parent function, and its parents, for the value of the variable, rather than using the value in the global environment?

推荐答案

问题是 Foo 是在全局环境中定义的.

The issue is that Foo is defined in the global environment.

添加行

  environment(Foo) <- environment()

Func1 Func2 中调用Foo之前​​,会产生所需的行为.

before calling Foo within Func1 and Func2 produced the desired behaviour.

这篇关于访问传递给父R函数或在父R函数中定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆