knitr:如何将子.Rnw文档与(相对)图形路径一起使用? [英] knitr: how to use child .Rnw docs with (relative) figure paths?
问题描述
我有一个父母和一个孩子Rnw
文档.子文档位于子文件夹children
中,即
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
现在,我想使用pdf
函数从子文档内部创建(边距)图形test.pdf
并将其放置在children
文件夹内的文件夹figure
中(即本地figure
文件夹)用于child.Rnw
).
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
).
父母.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
.
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
.
问题:如何为子 AND 父文档的编译提供正确的路径?
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
}
}
现在,我们将从父文档到子文档路径提供给函数adjust_path
.
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.
这篇关于knitr:如何将子.Rnw文档与(相对)图形路径一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!