0

I have a R script that should change the working directory using setwd().

My code:

setwd(file.path(work_dir, database_dir, study))

I can pause my script just before this line is supposed to execute (using browser()) enter the code into the console without issue, but whenever the line is executed from the script I get the error box stating that there is an "error while opening file: The system cannot find the file specified." Within my script before calling the setwd, I confirmed that the path exists using file.exists(file.path(work_dir, database_dir,study)). I also restarted R studio and closed and reopened all of my scripts to make sure that was not causing the problem.

Does anyone have any other suggestions for me to try?

Zoe
  • 27,060
  • 21
  • 118
  • 148
melmo
  • 757
  • 3
  • 15
  • Maybe I'm just confused, but why are you changing your working **directory** to a **file**path? – Greg Jul 09 '21 at 12:51
  • The file.path() function constructs the path to a file from components in a platform-independent way. I've used it many times before without issue. – melmo Jul 09 '21 at 12:59
  • 1
    If the directory does not exist or if it is instead a file, I get the error `cannot change working directory`, not `cannot find`, suggesting that perhaps *that* line is not the line that is erring. (BTW, I use `file.path` all the time to create directory paths, I think the function name could instead be file/dir-agnostic such as `make.path` or `create.path` or similar ... but it's fine. You might instead use `dir.exists` instead of `file.exists`, it is both logically more consistent with your intent and will err if it is indeed a file when it should be a directory.) – r2evans Jul 09 '21 at 13:10
  • I agree that it is super weird that I am getting a "Error while opening file" error. I'm not sure what else to try. I've even removed the file.path and typed out the path to just the first subfolder manually to no avail. What I really don't understand is why the command works no problem in the console, but won't work from the script. – melmo Jul 09 '21 at 13:27

1 Answers1

0

Posting how I resolved the issue:

The script that changed the directory (I will call this script 2) was called by another script first (I will call this script 1). script 1 and script 2 are in the same directory, but different directories from where I where I was trying to change. script 1 called script 2 using source("script2.R"). When I changed this to source(file.path(work_dir, "script2.R")) I no longer had issues with the setwd() command. My GUESS is that when I changed directories Rstudio "forgot" what script it was supposed to be executing and that is why I got a "no file exists" error.

If anyone has any other thoughts - please share!

melmo
  • 757
  • 3
  • 15