knitr:如何使用child.使用(相对)数字路径的文档?

Mar*_*ann 5 r knitr

我有父母和子Rnw文件.子doc位于子文件夹中children,即

+-- parent.Rnw
+-- children
    +-- child.Rnw
    +-- figure
         +-- test.pdf
Run Code Online (Sandbox Code Playgroud)

现在我想test.pdf使用该pdf函数从子文档内部创建(边距)图形,并将其放在文件夹figure内的children文件夹中(即本地figure文件夹child.Rnw).

parent.Rnw

\documentclass{article}
\begin{document}
I am the parent
<<child, child='children/child.Rnw'>>=
@
\end{document}
Run Code Online (Sandbox Code Playgroud)

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} }
Run Code Online (Sandbox Code Playgroud)

编译时child.Rnw一切正常.子路径的路径figure/test.pdf是正确的,但在编译父文档时则不正确.然后它必须是children/figure/test.pdf.

问题:如何为孩子父文档编译提供正确的路径?

Mar*_*ann 7

对我来说,以下解决方案是合适的:在子文档的顶部,我定义了一个函数,根据文档是作为子项运行来调整相对路径:

# 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
  }  
}
Run Code Online (Sandbox Code Playgroud)

现在,我们提供了从父级到子级的doc路径到该函数adjust_path.

ap <- adjust_path("children")
Run Code Online (Sandbox Code Playgroud)

该函数返回一个新函数,可用于调整子doc中的相对路径.现在我们可以写了

\includegraphics[width=\textwidth]{\Sexpr{ap("figure/test.pdf")}} 
Run Code Online (Sandbox Code Playgroud)

如果作为子文档或独立文档运行,则路径将是正确的.