Your understanding of how source
works seems correct to me. But let's write an example so you can compare with your setup and maybe find where you went wrong.
Let the /Users/me/test/mother.R
file contain the following:
print("I am the mother")
print(paste("The current dir is:", getwd()))
source("grandmother.R") # local path
and let the /Users/me/test/grandmother.R
file contain the following:
print("I am the grandmother")
Where you start will help understand:
> getwd()
[1] "/Users/me"
This does not work:
> source("/Users/me/test/mother.R")
[1] "I am the mother"
[1] "The current dir is: /Users/me"
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file 'grandmother.R': No such file or directory
because R is looking for grandmother.R
in the getwd()
dir...
Instead,
> source("/Users/me/test/mother.R", chdir = TRUE)
[1] "I am the mother"
[1] "The current dir is: /Users/me/test"
[1] "I am the grandmother"
works because source()
temporarily changes the current directory to /Users/me/test/
where it can find grandmother.R
.
When source
gives you the handle back, you end up where you started, meaning the chdir
is local to the source
call like @CarlWitthoft pointed out.
> getwd()
[1] "/Users/me"