Search code examples
r-markdownpandocfigure

Using relative paths in Rmarkdown when knitting from two different locations


My problem is with use of relative links and "compiling" (knitting).

I'm writing a book using RMarkdown. Since the file will be relatively large, I need to split into subfiles and directories.

I have a masterfile which only includes links to chapters(chap1, chap2, ...). There is a file for each chapter and each needs references to some figures (fig1,...).

I would like to be able to knit masterfile.Rmd and chap1.Rmd independently from each others so to get one file for chapters, and one file for the whole book.

Here is how my files are organized (MVE). Directories are displayed in upper case.

  • ROOT
    • masterfile.Rmd
    • FIGURES
      • fig1.pdf
      • fig2.pdf
    • CHAPTERS
      • chap1.Rmd
      • chap2.Rmd
      • ...

The code of masterfile.Rmd is as follows:

{r child = '/chapters/chap1.Rmd'}

The code of chap1.Rmd is as follows:

![](../figures/fig1.pdf)

As I knit from chap1.Rmd, everything is fine. As I knit from masterfile, I get the following message:

[WARNING] Could not fetch resource '../figures/fig1.pdf': PandocResourceNotFound "../figures/fig1.pdf"

It seems that fig1.pdf cannot be found. I guess that this is because the include statement in master file only "copies" the code of chap1.Rmd and "executes" it in the ROOT directory (not in the CHAPTERS directory) so ".." drives to location that does not exist (before ROOT) when knitted from masterfile.

I could change the setting and write ![](/figures/fig1.pdf) in chap1.Rmd file. It would work fine when knitting from masterfile but no longer from chap1.Rmd.

Do you know how to have both?


Solution

  • Welcome to the RMarkdown community!

    Due to KnitR, Rmd, and pandoc inter-workings, this is not as easy of a solution as you'd think, but a directory restructure would almost be easier.

    Even if you look at Rmarkdown author's newest book RMarkdown CookbookHERE. They have all the chapters in the ROOT directory, and only sub directories for images(and possibly figures).

    resources:

    1. Other SO similar question

    2. Github options knitr question

    3. similar question from Rstudio community