【问题标题】:knitr: how to use child .Rnw docs with (relative) figure paths?knitr:如何将子 .Rnw 文档与(相对)图形路径一起使用?
【发布时间】:2014-10-21 14:35:19
【问题描述】:

我有一个父母和一个孩子Rnw 文档。子文档位于子文件夹children,即

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

现在我想使用pdf 函数从子文档内部创建(边距)图形test.pdf,并将其放在children 文件夹内的文件夹figure 中(即本地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父文档?

【问题讨论】:

  • 子文档中的路径对我来说是一场噩梦,我认为我永远没有时间或勇气来修复它们(或者也许无法修复它们,因为必须考虑LaTeX 和 R)。我建议将所有内容放在一个平面结构中,即父母和孩子在同一个目录中,并避免嵌套目录。
  • @Yihui, knitr 有没有办法在编译时知道当前编译的文档是否是子文档? IE。从子文档内部,R 有没有办法查看这是否是子文档?如果是这样,我将尝试使用 knitr 块生成路径,具体取决于文档是否为子文档。
  • 是的,有一个内部函数knitr:::child_mode()

标签: r knitr


【解决方案1】:

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

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

现在,我们将 from-the-parent-to-the-child-doc 路径提供给函数 adjust_path

ap <- adjust_path("children")

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

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

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

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2019-02-12
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多