Knitr: how to use child .Rnw docs with (relative) figure tracks?

I have a parent and child Rnw document. The children's document is located in the children subfolder, i.e.

 +-- parent.Rnw +-- children +-- child.Rnw +-- figure +-- test.pdf 

Now I want to create the number (margin) test.pdf from inside the child document using the pdf function and put it in the figure folder inside the children folder (i.e. the local figure folder for child.Rnw ).

parent.Rnw

 \documentclass{article} \begin{document} I am the parent <<child, child='children/child.Rnw'>>= @ \end{document} 

child.Rnw

 <<parent, echo=FALSE, cache=FALSE>>= knitr::set_parent("../parent.Rnw") @ I am the child doc. <<>>= pdf("figure/test.pdf") plot(1:10) dev.off() @ \marginpar{ \includegraphics[width=\marginparwidth]{figure/test.pdf} } 

When compiling child.Rnw everything works fine. The path to figure/test.pdf correct for the child document, but not when compiling the parent document. Then it should be children/figure/test.pdf .

Question: How can I find the correct path to compile the child AND parent document?

+5
source share
1 answer

The following solution suits me: At the top of the child document, I define a function that adjusts the relative path depending on whether the doc is executed 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 pass the path from-the-parent-to-child-doc to the adjust_path function.

 ap <- adjust_path("children") 

The function returns a new function that can be used to set the relative path in the child document. Now we can write

 \includegraphics[width=\textwidth]{\Sexpr{ap("figure/test.pdf")}} 

and the path will be correct if you execute it as a child or standalone document.

+6
source

Source: https://habr.com/ru/post/1205191/


All Articles