This is a bit tricky for me to describe but please see the example below. I am trying to isolate scope of some R scripts by loading the scripts into a function. But this doesn't work when loading 'nested' functions. Per example below, the function 'inside' can be called after being loaded, but then the function 'outside' errors out saying it can not find the function 'inside.'
#this would be in some file
inside <- function(a, b){
return(a+b)
}
outside <- function(c, d){
inside(c, d)
}
save.image("my_r_functions.model")
rm(list = ls())
#this would be in some other file
wrapper <- function(d, e){
load("my_r_functions.model")
print(paste('inside works: ', inside(d,e)))
print('but outside can not find inside')
outside(d,e)
}
wrapper(1,2)
output:
[1] "inside works: 3"
[1] "but outside can not find inside"
Error in outside(d, e) : could not find function "inside"
You didn't specify where you wanted it loaded. Just add envir=globalenv()
(or envir=environment(wrapper)
) to the call to load.
wrapper <- function(d, e){
load("my_r_functions.model",envir=environment(wrapper))
print(paste('inside works: ', inside(d,e) ))
print('but outside can not find inside')
outside(d,e)
}
wrapper(1,2)
will work
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments