I've seen a few questions about this, but can't work out how to do what I want.
By default, Sweave creates graphics by concatenating the name of the Rnw file and the name of the graphic object label.
From this question (Make Sweave + RweaveHTML put all graphics in a specified folder) If I want all my graphics in the folder foo and to be named bar-graphic I can use
\SweaveOpts{prefix.string=foo/bar}
But how can I get the graphics in folder foo but named rnwfile-graphic ?
OK, this probably should be assigned to the innermost circle of hell, but the only way I know of to get the name of the currently running script is to use (abuse?) the source reference attached to functions. Consider this Sweave chunk in a file foo.Rnw
<<>>=
foo <- function(x) {x}
srcref <- attr(body(foo), "srcref")[[1]]
attr(srcref, "srcfile")$filename
@
When I process foo.Rnw
with Sweave I get:
\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}
You could make a dummy function at the top of your Sweave file, pull out the $filename
from the source reference, and process it to remove the extension, e.g.:
> sub("\\.Rnw", "", "foo.Rnw")
[1] "foo"
and then build up the string needed for prefix.string
, with say
<<>>=
fname <- sub("\\.Rnw", "", attr(srcref, "srcfile")$filename)
prefix.string <- paste("foo/", fname, "-graphic", sep = "")
@
\SweaveOpts{prefix.string=\Sexpr{prefix.string}}
where prefix.string
contains the built up path and prefix.
Here is a complete example:
<<>>=
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)
@
that when processed by Sweave gives:
\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}
Tweak that as you see fit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With