Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R在调用时获取由函数创建的环境_R_Scope - Fatal编程技术网

R在调用时获取由函数创建的环境

R在调用时获取由函数创建的环境,r,scope,R,Scope,我想在运行函数时获得函数创建的环境,而不修改函数源(即从函数外部),是否可能 fn=function() {#Here a new environment is created at each call, how to get it ? #This environment can be access with environment() but only (to what I know) #from inside the function ... } 我想要这样的东西: env=s

我想在运行函数时获得函数创建的环境,而不修改函数源(即从函数外部),是否可能

fn=function()
{#Here a new environment is created at each call, how to get it ?
 #This environment can be access with environment() but only (to what I know) 
 #from inside the function

  ...
}
我想要这样的东西:

env=some_function(fn())

其中env是fn在调用时创建的环境id。

您可以跟踪函数以将调用环境绑定到全局环境中的符号:

fn <- function() {x <- 2; 1}
trace(fn, quote(efn <<- environment()), at = 1)
fn()
#Tracing fn() step 1 
#[1] 1
untrace(fn)
efn$x
#[1] 2

fn您能否提供一个示例,说明如何使用此函数?我不确定您希望从这个函数返回什么?@ColinFAY这里很难完全解释,但简而言之,我正在测试一些调试过程。有没有建议将其封装在函数中,例如efn=some_fn(fn())?好的,我已经知道了如何做=>trace(as.character(substitute(…)[1])