Question

I would like to run function X and store all variables used in this function into my environment so that I can access them straight from the console or other scripts. I know, it is not recommended to use global variables, but I need it to improve the code.

Example:

Toy.R

executeToy <-function(time){
X = 2+time
W = 2
}

ToyCall.R

source('Toy.R')
Y = X+2
Was it helpful?

Solution

This returns a list of all variables in the functions environment:

executeToy <-function(time){
  X = 2+time
  W = 2
  mget(ls())
}

executeToy(1:3)
#$time
#[1] 1 2 3
#
#$W
#[1] 2
#
#$X
#[1] 3 4 5

However, from your comments I believe the browser function (which steps through an expression, i.e., is usually used for debugging) would be more useful to you.

Example:

executeToy <-function(time){
  browser()
  X = 2+time
  W = 2
  X
}

Then call the function:

> executeToy(1:3)
Called from: executeToy(1:3)
Browse[1]> time
[1] 1 2 3
Browse[1]> n
debug at #3: X = 2 + time
Browse[2]> n
debug at #4: W = 2
Browse[2]> X
[1] 3 4 5
Browse[2]> n
debug at #5: X
Browse[2]> W
[1] 2
Browse[2]> n
[1] 3 4 5

OTHER TIPS

To return all variables from Toy.R in a list:

executeToy <-function(time){
X = 2+time
W = 2
result <- list(ls()) #updated
return(result)
}

If you want to return only X:

executeToy <-function(time){
X = 2+time
W = 2
return(X)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top