Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...