Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set current file location as work directory in R markdown?

Tags:

r

r-markdown

I have mydata.RDATA to be used in R, then I need to load(), which means I need to setwd() curent directory first. I already know how to do it in R.

When I do it in R markdown:

{r echo=FALSE} dirname(parent.frame(2)$ofile) script.dir <- dirname(sys.frame(1)$ofile) setwd(script.dir)

I get error as below:

Error in dirname(parent.frame(2)$ofile) : a character vector argument expected calls :<Anonymous>...

like image 290
kittygirl Avatar asked Sep 10 '25 10:09

kittygirl


1 Answers

If your .Rmd file is in a subfolder you need to specify the root directory for knitr, even if you've specified a working directory with setwd() or even an RSudio project.

Fortunately this is as easy as adding the following chunk to the start of your .Rmd file, right after the YAML:

{r "setup", include=FALSE} require("knitr") opts_knit$set(root.dir = "~/path/to/project")

The ~/ is your HOME directory on Linux (and maybe Mac). If you're on Windows you'll have to tweak this.

like image 159
Phil Avatar answered Sep 12 '25 23:09

Phil