Reputation: 1381
if I have a function in R
f <- function(){
x <- 3
}
then when I execute the function in an interactive session, like this
> f()
>
the variable x is not defined/accessible
> x
Error: object 'x' not found
>
Is there a way to execute f as if the contents of the function were entered line by line into the interactive session?
EDIT: Here is the reason why I would like this functionality. I have a collection of scripts that I use to semi-automate a multi-step analysis workflow. To use them, I usually source a scripts and it initializes a session with pre-processed data. Then I can interactively continue the analysis from there.
In order to attach meta-data to the scripts, I have wrapped the analysis scripts as S4 objects implementing a base class. Currently I have the contents of each script in a member function called run() that can be executed. The issue is that while I can execute the run() function to preform the initial analysis computation, it cannot setup the environment with the pre-processed data.
Upvotes: 2
Views: 839
Reputation: 40813
No, I don't believe that it is possible. UPDATE Well, I now believe it is possible. See below.
When the function f
is executed, a local environment is created that initially has the parameter values (none in your case). The assignment to x
happens in that local environment.
If you modify f
you can achieve what you want though. Here are a couple of alternatives:
# Simply return the value:
f <- function() {
x <- 3
x # returns x. return(x) also works fine.
}
f() # returns 3
# Assign to global env
f <- function() {
x <<- 3 # Assigns in global env - but see help("<<-") for details
}
f()
x # 3
# Return the local environment
f <- function(foo=13) {
x <- 3 # local assignment
environment() # return the local environment
}
e <- f()
e$x # 3
e$foo # 13
Note that your original version of f
also returned 3, but invisibly - the default result from an assignment is an invisible value. There is also a special function, invisible
for that:
f <- function(){
x <- 3
}
print( f() ) # 3
a <- f()
a # 3
invisible(42) # won't show...
print( invisible(42) ) # ...but it's there!
UPDATE Thinking about it a bit more, of course it is possible. Let's make a slightly more interesting function:
f <- function(a, b) {
cat("I got",a,"and",b,"\n")
x <- a+b
}
# Ensure there is no x to prove that the following works...
rm(x)
# First assign the input parameters to f.
a <- 5
b <- 3
# Then evaluate the body.
eval(body(f))
x # 8
Upvotes: 3