kholsman/ACLIM2

need to use local=TRUE when source'ing scripts

wStockhausen opened this issue · 2 comments

Scripts like make.R source other scripts in the repo. When "source" is called on a script (e.g. source("pathToMyScript/myScript.R")), the script is evaluated in the global environment, so all paths for sourcing scripts (i.e., pathToMyScript) anywhere in the ACLIM2 project folder have to be relative to the current working directory. As the project seems to be set up now, the working directory has to be the ACLIM2 project folder because all(?) paths in scripts that source other scripts are relative to it. However, it seems more likely that users will probably create their own folders from which to work--probably not even within the ACLIM2 project directory structure (particularly if you cloned the ACLIM2 project--why add your own project-specific code to the repo when it may be erased of you do a pull to update the ACLIM2 project itself).

The solution is to use 'source' with "local=TRUE": e.g.,
source('relPathToScriptFromCurrentScript/script.R',local=TRUE)
where relPathToScriptFromCurrentScript is the relative path from the calling script to the sourced script.R. This evaluates the call to "source" in the calling script's environment, so all the calling script needs to know is what the (relative) path is from it to the script it wants to source. This makes the source'ing independent of the current working directory.

Note that users should also (probably) change the variable "main" when setting up their workspace so it is the path to the ACLIM2 project folder on their system, not their current working directory. Many paths defined for saving data files (e.g., GIS data files) seem to be predicated on "main" being the ACLIM2 project folder.

OK, so in order for the local=TRUE option to work, you need to make the scripts functions, rather than scripts, so that the calls to "source" work in the environment of the calling function. As set up now with scripts, the calling environment is the global environment. To keep using scripts, and assuming the user sets "main" to the ACLIM2 project folder, the paths for scripts need to include main: e.g., source(file.path(main,relPathFromACLIM2ProjectFolder,"script.R")).