Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr: how to use child .Rnw docs with (relative) figure paths?

Tags:

r

knitr

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

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

Now I want to create the (margin) figure test.pdf from inside the child doc using the pdf function and place it in the folder figure 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 the child.Rnw everything works fine. The path to figure/test.pdf is correct for the child doc but not when compiling the parent doc. Then it would have to be children/figure/test.pdf.

Question: How can I have a correct path for the compilation of the child AND the parent doc?

like image 307
Mark Heckmann Avatar asked Oct 21 '14 14:10

Mark Heckmann


1 Answers

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.

like image 119
Mark Heckmann Avatar answered Nov 15 '22 04:11

Mark Heckmann