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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With