Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

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

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}
egin{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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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=extwidth]{Sexpr{ap("figure/test.pdf")}} 

and the path will be correct if run as a child or standalone document.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...