好的,这可能应该分配到地狱的最内圈,但我知道获取当前正在运行的脚本名称的唯一方法是使用(滥用?)附加到函数的源引用。考虑文件中的这个 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}
调整你认为合适的。