Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

source(..., chdir=TRUE) does not seem to change the directory

Tags:

r

chdir

I'm pretty new to R and I'm trying to source a file which is again sourcing files. So I have a file, lets call it mother.R which contains a source call:

source ("grandmother.R")

mother.R and grandmother.R are in the same directory.

I would now like to source mother.R:

source ("C:/Users/whatever/R/mother.R", chdir=T)

My assumption was that the chdir=T would cause the source within the source to be looked for under C:/Users/whatever/R/, but it does not find grandmother.R when sourcing like this. Do I missunderstand chdir? Is there a way to do this without have to use absolute paths in mother.R?

like image 297
chuelibrueder Avatar asked Oct 23 '13 11:10

chuelibrueder


1 Answers

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"
like image 189
flodel Avatar answered Nov 03 '22 22:11

flodel