简体   繁体   中英

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:

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:

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. However, I am looking for a way to get such internal objects from any existing function. Therefore, I tried debug() and environment() without success. Any ideas or directions on how to obtain internal objects from a function would be appreciated.

I guess one easy way to modify an existing function is to use the trace() debugging tool. 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

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

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()
# [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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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