When you open or create a project in RStudio, the working directory is automatically changed to that of the project. However, if you are saving files or doing work in other subdirectories, it's often convenient to change the working directory then. It can get to be a pain to manage this in every script.
Is there a variable that always points to the project root (that is also readable by the session forked by the "Knit HTML" button) that can be used to make this easier?
The "Knit HTML" button appears to set the working directory to that of the R Markdown file. For example, if you have a variable called project.root
in your ./Rprofile
, and you click "Knit HTML" with this script opened,
```{r}
getwd()
source('./Rprofile')
setwd(project.root)
getwd()
```
the first and last result will be the script directory and the rest will throw errors.
To recap, as you inferred, you can set R's working directory at the command line like so:
setwd("~/NateProjects")
You can also use RStudio's Files pane to navigate to a directory and then set it as working directory from the menu: Session --> Set Working Directory --> To Files Pane Location. (You'll see even more options there). Or within the Files pane, choose More and Set As Working Directory.
But, you can do better & set up an environment like a professional programmer. To do this, you can choose to keep all the files associated with a project (a project being loosely defined as I have all my personal code under one project) organized together -- input data, R scripts, analytical results, figures. In fact, RStudio has built-in support for this. There is an excellent tutorial here that you can have a look at which explains how to walk through in step by step detail:
http://www.rstudio.com/ide/docs/using/projects
Essentially, taking from the documents, you need to do the following:
Then, once you create this new project in RStudio, the following actions happen: