简体   繁体   English

将a R function 产生的对象带到主工作环境

[英]Bring the objects produced by a R function to the main working environment

I am trying to inspect the internal objects produced by a R function such as the example below:我正在尝试检查 R function 生成的内部对象,如下例所示:

myfunction <- function(arg1, arg2){
sum.both <- arg1+arg2
diff.both <- arg1-arg2
return(diff.both)
}

I am aware that I can bring it to the working environment by modifying the function itself:我知道我可以通过修改 function 本身将它带到工作环境中:

myfunction.mod <- function(arg1, arg2){
sum.both <- arg1+arg2
sum.both <<- sum.both
diff.both <- arg1-arg2
return(diff.both)
}

myfunction.mod(1,2)

By doing that I can see the sum.both object by typing ls() in the console.通过这样做,我可以通过在控制台中键入ls()来查看sum.both object。 However, I am looking for a way to get such internal objects from any existing function. Therefore, I tried debug() and environment() without success.但是,我正在寻找一种方法来从任何现有的 function 中获取此类内部对象。因此,我尝试了debug()environment()但没有成功。 Any ideas or directions on how to obtain internal objects from a function would be appreciated.任何有关如何从 function 获取内部对象的想法或指示将不胜感激。

I guess one easy way to modify an existing function is to use the trace() debugging tool.我想修改现有 function 的一种简单方法是使用trace()调试工具。 We can use that to insert code that will run at exit of a function to "leak" all the values from the function scope into the global scope. Here's such a function我们可以使用它来插入将在 function 退出时运行的代码,以将 function scope 中的所有值“泄漏”到全局 scope 中。这是一个 function

make_leaky <- function(f) {
  fn <- substitute(f)
  invisible(trace(fn, print=FALSE, exit=quote(list2env(mget(ls()), globalenv()))))
}

Then we can test it with the following function然后我们可以用下面的function来测试一下

foo <- function(x, y) {
  a <- x+7
  b <- x*y
  b/a
}

We will use ls() to see all the variables at each step我们将使用ls()查看每一步的所有变量

ls()
# [1] "foo"        "make_leaky"
foo(5,2)
# [1] 0.8333333
ls()    # NO NEW VARIABLES CREATED HERE
# [1] "foo"        "make_leaky"   
make_leaky(foo) 
foo(5,2)
# [1] 0.8333333
ls()   # ALL VARIABLES FROM FOO ARE NOW IN GLOBAL ENV
# [1] "a"          "b"          "foo"        "make_leaky"
# [5] "x"          "y" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM