Search code examples
rlatexsweave

Sweave: use a chunk as a latex command parameter


Is it somehow possible with Sweave to define a Latex-command and pass the results from a chunk as parameter?

Basically I want to create something like in this example:

\newcommand{\myCommand} [1] {
    \begin{figure} 
      \begin{center}
        #1
      \end{center}
    \end{figure}
}

\myCommand{
   <<fig=TRUE, results=hide>>
      plot(1:10,1:10)
   @
}

Solution

  • The output of a plot chunk is an includegraphics command in resulting .tex file :

    \includegraphics[width=\maxwidth]{figure/testPlot}
    

    So your new command should work (with corrected syntax here) : when the chunk is evaluated, the includegraphics is wrote to the .tex file. After this step, the latex code is evaluated, with all your commands and options.

    \documentclass{article}
    \begin{document}
    \newcommand{\myCommand} [1] {
        \begin{figure}[t] 
          \begin{center}
            #1
          \end{center}
        \end{figure}
    }
    \myCommand{
       <<testPlot>>=
          plot(1:10,1:10)
       @
    }
    \end{document}
    

    UPDATE This solution works only with knitr :

    Rscript -e "library(knitr);knit('myFile.Rnw')"
    

    Or to produce a pdf :

    Rscript -e "library(knitr);knit2pdf('myFile.Rnw')"
    

    With Rstudio, please read this : Weaving .Rnw using rstudio