[R] User Defined R Functions in Sweave/Latex

Dieter Menne dieter.menne at menne-biomed.de
Thu Jun 21 08:57:22 CEST 2007


M. Jankowski <mjankowski <at> gmail.com> writes:

> My Sweave code is intended to make lots of plots and create a *.pdf
> document. Sweave is perfect for this. The only problem is that  I find
> myself using the same R code, within my Sweave input file over an
> over. 
....
 
> This is the R function:
> basicplot <- function(x, nplots, sectionname){
> # Begin to make figure here
> file = paste("scatter",nplots, ".pdf", sep="")
> pdf(file = file,paper="special", width=6, height = 6)
> plot(x)
> dev.off()
> cat("\\begin{figure}\n")
> cat("\\includegraphics{",file,"}\n", sep="")
> cat("\\caption{", sectionname,"}\n", sep = "")
> cat("\\end{figure}\n")
> #End figure making
> }
> 
I don't know if this is exactly what you want, but below an example of using
includegraphics in a latex macro. For a real application, I recommend
\FloatBarrier instead of \clearpage when you have lots of figures/tables and
little text, as it's common in technical stuff.

Dieter

% -- Begin Sweave example
\documentclass[a4paper]{article}
\usepackage{Sweave}
\SweaveOpts{engine=R,eval=TRUE,eps=FALSE,pdf=TRUE, strip.white=TRUE}
\SweaveOpts{echo=FALSE,results=hide,width=6,height=4}

\bibliography{menne}
\begin{document}
\section{Hello}

\newcommand\doaplot[3]{

\begin{figure}
  \centering
\subsection{ #1}
\includegraphics{#2}
  \caption{3}
  \label{fig:#2}
\end{figure}
The meaning of life is The meaning of life is
The meaning of life is
The meaning of life is
The meaning of life is
\clearpage

}

<<dotheplots, results=tex>>=
 for (nplots in 1:3) {
   file = paste("scatter",nplots, ".pdf", sep="")
   pdf(file = file,paper="special", width=6, height = 6)
   plot(rnorm(100),rnorm(100),main=paste("Plot",nplots))
   dev.off()
   cat("\\doaplot{Section",nplots,"}{scatter",nplots,"}{My caption for ",
     nplots,"}\n",sep="")
 }
@

\end{document}



More information about the R-help mailing list