gpt4 book ai didi

r - 如何让 Sweave 将图形放在单独的文件夹中并以 Rnw 文件命名它们

转载 作者:行者123 更新时间:2023-12-04 11:16:30 26 4
gpt4 key购买 nike

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

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

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

\SweaveOpts{prefix.string=foo/bar}

但是如何在文件夹 foo 中获取名为 rnwfile-graphic 的图形?

最佳答案

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

哪里 prefix.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}

根据您的需要调整它。

关于r - 如何让 Sweave 将图形放在单独的文件夹中并以 Rnw 文件命名它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7254228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com