There are multiple possibilities to achieve this, depending on how far you want to go. The most easy way is simply to assign the variable W in the global environment, and call the other scripts from there. This does defeat the purpose of a function though.
The most straight-forward solution would to use the option local=TRUE
in the source
call. This allows the sourced script to search in the local environment of the function.
An illustration : given a file Myscript.r :
cat("In script : ",x," ",W,"\n")
afunc <- function(y){
cat("within function : ",y," ",W,"\n")
}
afunc(x)
You can define a function that sources it locally :
mynewfunc <- function(x){
W <- "My W"
source("Myscript.R",local=TRUE)
}
avar <- "Working in R"
mynewfunc(avar)
And does what it needs to do : It finds the x
that got passed from the global environment to mynewfunc
, and it finds the W
assigned in the local environment of mynewfunc
:
In script : Working in R My W
within function : Working in R My W
The most robust option would be though to do this in a package. Basically you declare them in one of the source files of your package. The constant W will be loaded and can be used by all functions in that package. If you work with namespaces, you can decide whether you want to export the constant, or keep it hidden so it can only be accessed by your own functions. More information on this you'll find in "Writing R extensions".
Sourcing script files within functions is a less robust way of dealing with different functions. You can get very unexpected results, depending on the vars in your workspace. If you want to try this, I definitely suggest you to start looking into constructing your own packages. It's pretty straightforward if there's no C code involved.