3

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

kittygirl
  • 2,255
  • 5
  • 24
  • 52
  • I really recommend using RStudio projects and relative paths. I also use the `ofile` approach in some legacy code but it is very unreliable, depending on where from the file is sourced, knitted, etc. – snaut Jun 14 '17 at 09:09
  • I use Rstudio, but never used project.I have 500+ project, then I can only store .Rdata file in each file folder. – kittygirl Jun 14 '17 at 13:14
  • Yes, you just have to open the project file, then the working directory is automatically set, and the files you had opend the last time in this project are opened. – snaut Jun 16 '17 at 07:09

1 Answers1

2

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.

Phil
  • 4,344
  • 2
  • 23
  • 33