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
526 views
in Technique[技术] by (71.8m points)

r - Setting work directory in knitr using opts_chunk$set(root.dir = ...) doesn't work

My R project is structured like a package with directories /R, /vignettes, /data etc. In one of my Rmd docs in /vignettes I source a script which in located in /R. Inside this script I use read.csv() to load a file located in inst/extdata/.
The problem now is that by default the working directory inside the Rmd file is the directory where the file is located. Let's call it /Users/Me/Docs/Proj/vignettes. However in order for the R script to run the working directory needs to be the project's main directory (/Users/Me/Docs/Proj).
I tried to change the working directory in the Rmd file using knitr::opts_chunk$set(root.dir = normalizePath(".."). However apparently this doesn't change the working directory since if I call getwd() after it the output is still /Users/Me/Docs/Proj/vignettes whereas knitr::chunk_opts$get("root_dir") returns /Users/Me/Docs/Proj.

Here is a minimal example Rmd file:

```{r}
getwd()  # returns 'Users/Me/Docs/Proj/vignettes'
knitr::opts_chunk$set(root.dir = normalizePath(".."))  # should change the working directory to 'Users/Me/Docs/Proj'
getwd()  # again returns 'Users/Me/Docs/Proj/vignettes'
knitr::opts_chunk$get("root.dir")  # returns 'Users/Me/Docs/Proj'
```

I am using RStudio Version 0.99.435. Here is my session Info:

R version 3.2.0 (2015-04-16)  
Platform: x86_64-apple-darwin14.3.0 (64-bit)  
Running under: OS X 10.10.3 (Yosemite)  

locale:
[1] de_DE.UTF-8/de_DE.UTF-8/de_DE.UTF-8/C/de_DE.UTF-8/de_DE.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] htmltools_0.2.6 tools_3.2.0     yaml_2.1.13     rmarkdown_0.6.1 digest_0.6.8   

Any help is kindly appreciated. If you need more info post a comment to the question. Thanks in advance!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It is knitr::opts_knit instead of knitr::opts_chunk.


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

...