Question

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.

Was it helpful?

Solution

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:

  • Create a new project use the Create Project command (available on the Projects menu and on the global toolbar). This can be the place that you put all future sub projects and sub-folders in

Then, once you create this new project in RStudio, the following actions happen:

  • You create a project file (with an .Rproj extension) within the project directory. This file contains various project options (discussed below) and can also be used as a shortcut for opening the project directly from the filesystem.
  • You create a hidden directory (named .Rproj.user) where project-specific temporary files (e.g. auto-saved source documents, window-state, etc.) are stored. This directory is also automatically added to .Rbuildignore, .gitignore, etc. if required.
  • You load the project into RStudio and display its name in the Projects toolbar (which is located on the far right side of the main toolbar)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top