5

我已经看到了一些关于此的问题,但无法弄清楚如何做我想做的事。

默认情况下,Sweave 通过连接 Rnw 文件的名称和图形对象标签的名称来创建图形。

从这个问题(Make Sweave + RweaveHTML put all graphics in a specified folder)如果我想要文件夹 foo 中的所有图形并命名为 bar-graphic 我可以使用

\SweaveOpts{prefix.string=foo/bar}

但是我怎样才能在文件夹 foo 中获取名为 rnwfile-graphic 的图形?

4

2 回答 2

5

好的,这可能应该分配到地狱的最内圈,但我知道获取当前正在运行的脚本名称的唯一方法是使用(滥用?)附加到函数的源引用。考虑文件中的这个 Sweave 块foo.Rnw

<<>>=
foo <- function(x) {x}
srcref <- attr(body(foo), "srcref")[[1]]
attr(srcref, "srcfile")$filename
@

当我foo.Rnw使用 Sweave 进行处理时,我得到:

\begin{Schunk}
\begin{Sinput}
> foo <- function(x) {
+     x
+ }
> srcref <- attr(body(foo), "srcref")[[1]]
> attr(srcref, "srcfile")$filename
\end{Sinput}
\begin{Soutput}
[1] "foo.Rnw"
attr(,"encoding")
[1] "ASCII"
\end{Soutput}
\end{Schunk}

您可以在 Sweave 文件的顶部创建一个虚拟函数,从源引用中拉出$filename,并对其进行处理以删除扩展名,例如:

> sub("\\.Rnw", "", "foo.Rnw")
[1] "foo"

然后建立所需的字符串prefix.string,例如

<<>>=
fname <- sub("\\.Rnw", "", attr(srcref, "srcfile")$filename)
prefix.string <- paste("foo/", fname, "-graphic", sep = "")
@

\SweaveOpts{prefix.string=\Sexpr{prefix.string}}

whereprefix.string包含构建的路径和前缀。

这是一个完整的例子:

<<>>=
foo <- function(x) {x}
srcref <- attr(body(foo), "srcref")[[1]]
attr(srcref, "srcfile")$filename
@

<<>>=
fname <- sub("\\.Rnw", "", attr(srcref, "srcfile")$filename)
prefix.string <- paste("foo/", fname, "-graphic", sep = "")
@

\SweaveOpts{prefix.string=\Sexpr{prefix.string}}

<<fig=TRUE>>=
plot(1:10)
@

当由 Sweave 处理时给出:

\begin{Schunk}
\begin{Sinput}
> foo <- function(x) {
+     x
+ }
> srcref <- attr(body(foo), "srcref")[[1]]
> attr(srcref, "srcfile")$filename
\end{Sinput}
\begin{Soutput}
[1] "foo.Rnw"
attr(,"encoding")
[1] "ASCII"
\end{Soutput}
\end{Schunk}

\begin{Schunk}
\begin{Sinput}
> fname <- sub("\\.Rnw", "", attr(srcref, "srcfile")$filename)
> prefix.string <- paste("foo/", fname, "-graphic", sep = "")
\end{Sinput}
\end{Schunk}



\begin{Schunk}
\begin{Sinput}
> plot(1:10)
\end{Sinput}
\end{Schunk}
\includegraphics{foo/foo-graphic-003}

调整你认为合适的。

于 2011-08-31T16:09:19.477 回答
3

虽然 Gavin 的 hack 很棒,但如果您真的希望 Sweave 做不同类型的事情,最好的方法是编写自己的驱动程序;例如,我使用这种方法让 Sweave 以不同方式缩放不同的图形。您不必从头开始,只需根据需要修改现有代码。

对于这种情况,只有几个小功能需要更改,但是,由于名称空间问题,从所有 Sweave 代码开始会更容易;您可以在此处获取 2.13 Sweave 代码

必要的更改如下。他们添加了一个新选项 ,subdir并将其添加到原始chunkprefixrnw 文件的名称之前。该SweaveParseOptions行是必需的,因为此函数不是由导出的utils,而是在不同的源文件中。

16a17,18
> SweaveParseOptions <- utils:::SweaveParseOptions
> 
69c71
<                     concordance = FALSE, expand = TRUE, figs.only = FALSE)
---
>                     concordance = FALSE, expand = TRUE, figs.only = FALSE, subdir=".")
520c522
<                    "grdevice")
---
>                    "grdevice", "subdir")
568c570
<     chunkprefix
---
>     file.path(options$subdir, chunkprefix)

将更改另存为SweaveDriversNew.R,将选项放入您的Rnw文件中,如下所示

\SweaveOpts{subdir=foo}

然后像这样使用新的驱动程序 Sweave。

source("SweaveDriversNew.R")
Sweave("test.Rnw", driver=RweaveLatex)

结果是图像被命名为foo/test-graphic.pdf,其中foo在 Sweave 文件中定义,并test自动取自 Sweave 文件的名称。

于 2011-09-01T14:33:42.700 回答