knitr: how to use child .Rnw docs with (relative) figure paths?
For me the following solution is suitable:
At the top of the child doc, I define a function that adjusts a relative path depending on whether the doc is run as a child or not:
# rp: a relative path
adjust_path <- function(path_to_child_folder, rp)
{
is.child <- knitr:::child_mode()
function(rp)
{
if (is.child)
rp <- file.path(path_to_child_folder, rp)
rp
}
}
Now, we supply the from-the-parent-to-the-child-doc path to the function adjust_path
.
ap <- adjust_path("children")
The function returns a new function which can be used to adjust a relative path in a child doc. Now we can write
\includegraphics[width=\textwidth]{\Sexpr{ap("figure/test.pdf")}}
and the path will be correct if run as a child or standalone document.
Source nested R files within Rmarkdown document
The issue you're facing is not related to knitr
or being able to correctly nest the documents but is instead a product of the R project "working directory insanity" one faces asrmarkdown
will knit the document relative to the file directory as opposed to the project root. This leads to different relative paths depending on whether the document is run in the project session or knitr
session.
In addition to the gist, this issue shows a number of workarounds:
knitr specific:
Set a root directory for all chunks to be evaluated relative to rather than the document location.
opts_knit$set(root.dir = '/Users/username/path_to_project')
General case:
Use either rprojroot
or here
(the latter is a wrapper over the former), which uses several criteria to determine the top level directory of your files. You need not be using an RStudio project for this to work.
Any reference to another local file is called using here::here
which will resolve to the same location regardless of the subdirectory in which it's called.
source(here("functions.R"))
source(here("subdirectory", "DataDependency.R"))
source(here("subdirectory2", "furtheranalyis.R"))
This is probably a better solution as it doesn't rely on knitr
options. Alternatively you can set the root.dir
chunk using rprojroot
:
opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
provided you are using an RStudio project. If not, use rprojroot::find_root
with a specified criterion.
Related Topics
Keyboard Shortcut for Inserting Roxygen #' Comment Start
How to Retrieve the Most Repeated Value in a Column Present in a Data Frame
Ggplot2: How to Adjust Fill Colour in a Boxplot (And Change Legend Text)
Dplyr Filter() with SQL-Like %Wildcard%
Importing Wikipedia Tables in R
R Markdown Math Equation Alignment
Multiple Colors in a Facet Strip Background
Aggregating Multiple Columns in Data.Table
R Ggplot2 Center Align a Multi-Line Title
Export All User Inputs in a Shiny App to File and Load Them Later
Provide Shades Between Dates on X Axis
What/Where Are the Attributes of a Function Object
Ggplot Object Not Found Error When Adding Layer with Different Data