Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

r - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...