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

时间:2014-10-21 14:35:19

标签: r knitr

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

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

现在我想使用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}

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} }

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

问题:如何为儿童 AND 编制父文档提供正确的路径?

1 个答案:

答案 0 :(得分: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
  }  
}

现在,我们将从父级到子级文档路径提供给函数adjust_path

ap <- adjust_path("children")

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

\includegraphics[width=\textwidth]{\Sexpr{ap("figure/test.pdf")}} 

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

相关问题