Search code examples
rrstudio

Cant set working directory in R notebook chunk, strange error


I'm running into a strange problem. When I set my working directory from an R markdown chunk within an RStudio RMD file, by running the chunk, I am receiving the following error:

setwd('~/Users/Home/mypath/here')    

The working directory was changed to /Users/Home/mypath/here inside a notebook chunk. 
The working directory will be reset when the chunk is finished running. 
Use the knitr root.dir option in the setup chunk to change the the working directory for notebook chunks.

After I run this line of code from the chunk, and check getwd(), I get the following:

getwd()
"/Users/Home"

However, when I run setwd() from the console (literally copy and paste / run the code in the console), the working directory is changed.

I have never gotten this error using setwd() from a notebook chunk, and I setwd() from a notebook chunk on almost every RMD file I create. Why am I getting this error now, out of nowhere? It seems odd.


Solution

  • In RStudio, in the Knit dropdown menu, select Knit directory, then Current Working Directory. Then rerun setwd(...). This fixed the problem for me.