Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In RStudio/RMarkdown, how to setwd?

setwd in an Rmd file in RStudio does not appear to change the directory in subsequent chunks. Is there a way to set the working directory for good?

Example:

```{r} setwd("/tmp") getwd() ```  ```{r} getwd() ``` 

Output:

setwd("/tmp") getwd() ## [1] "/private/tmp"  getwd() ## [1] "/Users/me/src" 

This is on Mac OS 10.8.5 using RStudio 0.97.551, R version 3.0.2 and knitr version 1.5.

I wish to set the directory once for all subsequent chunks.

like image 699
user650654 Avatar asked Nov 19 '13 00:11

user650654


People also ask

What is Setwd command in R?

setwd returns the current directory before the change, invisibly and with the same conventions as getwd . It will give an error if it does not succeed (including if it is not implemented).

Why is Setwd not working in R?

The reason for this is that the directory we are trying to access does not exist. We might have specified the folder name wrong, or the path before the folder name is not existing.

How do I change the working directory in R Markdown?

The usual way to change the working directory is setwd() , but please note that setwd() is not persistent in R Markdown (or other types of knitr source documents), which means setwd() only works for the current code chunk, and the working directory will be restored after this code chunk has been evaluated.


2 Answers

See Issue #277 and for further background, the package author's comments here

What you are looking for is the root.dir option in knitr::opts_knit.

The following will set the root directory for subsequent code chunks (but not this chunk):

```{r setup} knitr::opts_knit$set(root.dir = '/tmp') ``` 

EDIT: RStudio 1.0.44

as of RStudio's latest release (Oct/Nov 2016), the following snippet is needed for knitr's render default:

```{r setup} knitr::opts_knit$set(root.dir = '/tmp') ``` 

see Etienne's comment about versions below.

like image 159
mnel Avatar answered Sep 22 '22 17:09

mnel


Here's what I've been using, and it seems to work well when using R Projects (.Rproj files):

knitr::opts_chunk$set(     # This should allow Rmarkdown to locate the data     root.dir = rprojroot::find_rstudio_root_file() ) 
like image 38
Matt Dancho Avatar answered Sep 21 '22 17:09

Matt Dancho