1

I have a project where I put .rmd files in a separate folder called docs. My R Markdown documents looks like this:

---
title: "test"
output: pdf_document
---
## R Markdown
```{r summary}
knitr::opts_knit$set(root.dir = normalizePath("../"))
source('../test.R')
```

My test.R script, sitting in the root folder, looks like this:

source('helloWorld.R')
print("Hello World")

And the helloWorld.R script looks like this:

print("Hello World from separate script")

My two questions are:

  1. Having set the root directory to "..", why do I still need to refer to the test.R using "../"?

  2. Why does the source-within-a-source fail? The above script works fine if I omit the source part of test.R?

lebelinoz
  • 4,890
  • 10
  • 33
  • 56
  • 1
    Source is always relative to the current working directory, not the file itself. If you want to source from the same file, maybe try the solution at this answer: http://stackoverflow.com/questions/42815889/r-source-and-path-to-source-files/42816729#42816729 – MrFlick Mar 20 '17 at 22:26
  • @MrFlick I appreciate the workaround: I might use it if I can't figure out how to set the working directory from within my R Markdown script. – lebelinoz Mar 20 '17 at 22:35
  • `setwd` will work within rmarkdown, although knitr might warn you about using it and will change back at the end of the chunk. In answer to your first question, knitr's `root_dir` is a knitr-specific option - it probably does not directly change the working directory. –  Mar 21 '17 at 06:19
  • @dash2 You're right! Thank you. If I replace my two lines of R code in my .rmd file with `setwd('..')` and `source('test.R')`, my script actually works just fine. – lebelinoz Mar 21 '17 at 22:00
  • @dash2 Can you put your comment into an answer so I can vote it as the correct one? – lebelinoz Mar 21 '17 at 22:11

1 Answers1

0

setwd will work within rmarkdown, although knitr might warn you about using it and will change back at the end of the chunk. In answer to your first question, knitr's root_dir is a knitr-specific option - it probably does not directly change the working directory.