0

For some reason, I am unable to set or change my working directory in my R-code itself. I'll include a line such as:

setwd("~/Documents/BeaverProject/HOBOData/Beav")

But it will be followed with an error:

Error in setwd("~/Documents/BeaverProject/HOBOData/Beav") : 
  cannot change working directory

However, if I go to the file browser tab in the bottom right corner, and click "(gear icon) More", it provides an option to "Set as Working Directory" which I can use to change the working directory to the desired file folder.

While this works, it means that I can't just sit back and allow my code sequence to run because I have to manually change the working directory at every point in the code where it needs to.

Any suggestions?

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25
jaynesw
  • 43
  • 7
  • 2
    Welcome to SO. My personal opinion is that it's not a good idea to change the working directory in your code. And if you do, you should always reset it to its original value at the end of the code. If you need to access resources outside the working directory, use absolute or relative paths. It might be helpful to assign frequently used paths to global variables and then reference individual resources by pasting path and resource name. – Limey Jun 07 '22 at 13:31
  • 2
    Are you on windows, by chance? If so, the premise of `~` is not always in concert with what unix/macos set them to be. Regardless, first check `dir.exists("~/Documents/BeaverProject/HOBOData/Beav")`, my suspicion is that it does not exist. You can see what R thinks it should be with `normalizePath("~/Documents/BeaverProject/HOBOData/Beav")`, perhaps it is different. – r2evans Jun 07 '22 at 13:31
  • 1
    If on Windows, try `"~/BeaverProject/HOBOData/Beav"`. The `~` by default will return the user's `Documents` directory so your attempt is being interpreted, for example, as `C:/Users/Name/Documents/Documents/...`. – Ritchie Sacramento Jun 07 '22 at 13:35
  • With thanks to @KonradRudolph for the link, [here](https://www.tidyverse.org/blog/2017/12/workflow-vs-script/) is a good discussion of why `setwd()` is not a good idea. Though I do think the authors threat to set your computer on fire is (a little) extreme. But only for a first offence. – Limey Jun 07 '22 at 14:38

0 Answers0