M. Jankowski
2007-Jun-21 03:50 UTC
[R] Need Help: User Defined R Functions in Sweave/Latex
Dear all, I want to start my post by expressing my sincere gratitude for all the help this group has given me in Sweave/Latex/R. The tools are excellent and so is the community! On to the question. 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. I know about Latex macros and I can even get R functions, essentially used as subroutines, to sort of work. "\Sexpr{}" will not work because the R code I want to use over and over is in the R environment. I've tried numerous ways to tackle this process and could really use some help. If there is some easier way to do this please let me know! 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 } The aim is to generate Latex code which will have some basic information as part of the caption. The trouble seems to be that the output from the function appears to latex as if it is protected R code when I really want to create output that pdflatex will act on. Essentially, the resulting *.pdf contains the lines output by the cat function in basicplot. Or: \begin{figure} \includegraphics{scatter1.pdf} \caption{myname} \end{figure} These lines are not in the environment acted by Latex. I tried a variant of the function where <<results=tex,echo=FALSE>> and received the same result. Below are the files *.Snw -> *.tex -> *.pdf and the output I received while compiling. If there is anything else I can give to help you help me just let me know. Thanks! Matt My system: T41 IBM Thinkpad Ubuntu Feisty (7.04) R version 2.5 testmacro3.Snw: mdj at lapmdj:~/mydocs/R$ more testmacro3.Snw \documentclass[a4paper]{article} \usepackage{fullpage} <<echo=f>>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 } @ \begin{document} Filler text here.\\ <<>>library("flowCore") x <- read.FCS("/home/mdj/data/yifacs2/NL7_PHA03_1.fcs", transformation = FALSE, alter.names = TRUE); basicplot(x, nplots = 1, sectionname="myname") @ End text here \\ \end{document} testmacro3.tex \usepackage{/usr/share/R/share/texmf/Sweave} \begin{document} Filler text here.\\ \begin{Schunk} \begin{Sinput}> library("flowCore")\end{Sinput} \begin{Soutput} Scalable Robust Estimators with High Breakdown Point (version 0.3-05) \end{Soutput} \begin{Sinput}> x <- read.FCS("/home/mdj/data/yifacs2/NL7_PHA03_1.fcs", transformation = FALSE, + alter.names = TRUE)> basicplot(x, nplots = 1, sectionname = "myname")\end{Sinput} \begin{Soutput} \begin{figure} \includegraphics{scatter1.pdf} \caption{myname} \end{figure} \end{Soutput} \end{Schunk} End text here \\ \end{document} testmacro3.pdf: Filler text here.> library("flowCore")Scalable Robust Estimators with High Breakdown Point (version 0.3-05)> x <- read.FCS("/home/mdj/data/yifacs2/NL7_PHA03_1.fcs", transformation = FALSE,+ alter.names = TRUE)> basicplot(x, nplots = 1, sectionname = "myname")\begin{figure} \includegraphics{scatter1.pdf} \caption{myname} \end{figure} End text here Output: mdj at lapmdj:~/mydocs/R$ R CMD Sweave testmacro3.Snw [1] "Welcome to my custom R eenvironment!"> library("utils"); Sweave("testmacro3.Snw")Writing to file testmacro3.tex Processing code chunks ... 1 : term verbatim 2 : echo term verbatim Loading required package: Biobase Loading required package: tools Welcome to Bioconductor Vignettes contain introductory material. To view, type 'openVignette()' or start with 'help(Biobase)'. For details on reading vignettes, see the openVignette help page. Loading required package: rrcov KernSmooth 2.22 installed Copyright M. P. Wand 1997 You can now run LaTeX on 'testmacro3.tex'> mdj at lapmdj:~/mydocs/Rpdflatex testmacro3.texThis is pdfeTeX, Version 3.141592-1.21a-2.2 (Web2C 7.5.4) entering extended mode (./testmacro3.tex LaTeX2e <2003/12/01> Babel <v3.8d> and hyphenation patterns for american, french, german, ngerman, b ahasa, basque, bulgarian, catalan, croatian, czech, danish, dutch, esperanto, e stonian, finnish, greek, icelandic, irish, italian, latin, magyar, norsk, polis h, portuges, romanian, russian, serbian, slovak, slovene, spanish, swedish, tur kish, ukrainian, nohyphenation, loaded. (/usr/share/texmf-tetex/tex/latex/base/article.cls Document Class: article 2004/02/16 v1.4f Standard LaTeX document class (/usr/share/texmf-tetex/tex/latex/base/size10.clo)) (/usr/share/texmf-texlive/tex/latex/preprint/fullpage.sty) (/usr/share/R/share/texmf/Sweave.sty LaTeX Warning: You have requested package `/usr/share/R/share/texmf/Sweave', but the package provides `Sweave'. (/usr/share/texmf-tetex/tex/latex/base/ifthen.sty) (/usr/share/texmf-tetex/tex/latex/graphics/graphicx.sty (/usr/share/texmf-tetex/tex/latex/graphics/keyval.sty) (/usr/share/texmf-tetex/tex/latex/graphics/graphics.sty (/usr/share/texmf-tetex/tex/latex/graphics/trig.sty) (/usr/share/texmf-tetex/tex/latex/graphics/graphics.cfg) (/usr/share/texmf-tetex/tex/latex/graphics/pdftex.def))) (/usr/share/texmf-texlive/tex/latex/fancyvrb/fancyvrb.sty Style option: `fancyvrb' v2.6, with DG/SPQR fixes <1998/07/17> (tvz) No file fancyvrb.cfg. ) (/usr/share/texmf/tex/latex/R/upquote.sty (/usr/share/texmf-tetex/tex/latex/base/textcomp.sty (/usr/share/texmf-tetex/tex/latex/base/ts1enc.def))) (/usr/share/texmf-tetex/tex/latex/base/fontenc.sty (/usr/share/texmf-tetex/tex/latex/base/t1enc.def)) (/usr/share/texmf-tetex/tex/latex/ae/ae.sty (/usr/share/texmf-tetex/tex/latex/base/fontenc.sty (/usr/share/texmf-tetex/tex/latex/base/t1enc.def) (/usr/share/texmf-tetex/tex/latex/ae/t1aer.fd)))) No file testmacro3.aux. (/usr/share/texmf-tetex/tex/latex/base/ts1cmr.fd) (/usr/share/texmf-tetex/tex/context/base/supp-pdf.tex (/usr/share/texmf-tetex/tex/context/base/supp-mis.tex loading : Context Support Macros / Miscellaneous (2004.10.26) ) loading : Context Support Macros / PDF (2004.03.26) ) Underfull \hbox (badness 10000) in paragraph at lines 6--8 (/usr/share/texmf-tetex/tex/latex/ae/t1aett.fd) Underfull \hbox (badness 10000) in paragraph at lines 26--27 [1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}] (./testmacro3.aux) ) (see the transcript file for additional information)</usr/share/texmf-tetex/fon ts/type1/bluesky/cm/cmtt10.pfb></usr/share/texmf-tetex/fonts/type1/bluesky/cm/c msltt10.pfb></usr/share/texmf-tetex/fonts/type1/bluesky/cm/cmr10.pfb> Output written on testmacro3.pdf (1 page, 26713 bytes). Transcript written on testmacro3.log. mdj at lapmdj:~/mydocs/R$ xpdf testmacro3.pdf & [4] 11100 mdj at lapmdj:~/mydocs/R$ Warning: Attempt to remove nonexistent passive grab xpdf testmacro3.pdf & [5] 11109 [4] Done xpdf testmacro.pdf mdj at lapmdj:~/mydocs/R$
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}
Marc Schwartz
2007-Jun-21 12:55 UTC
[R] Need Help: User Defined R Functions in Sweave/Latex
On Wed, 2007-06-20 at 22:50 -0500, M. Jankowski wrote:> Dear all, > > I want to start my post by expressing my sincere gratitude for all the > help this group has given me in Sweave/Latex/R. The tools are > excellent and so is the community! > > On to the question. > > 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. I know about Latex macros and I can even get R functions, > essentially used as subroutines, to sort of work. "\Sexpr{}" will not > work because the R code I want to use over and over is in the R > environment. I've tried numerous ways to tackle this process and could > really use some help. If there is some easier way to do this please > let me know! > > 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 > } > > The aim is to generate Latex code which will have some basic > information as part of the caption. The trouble seems to be that the > output from the function appears to latex as if it is protected R code > when I really want to create output that pdflatex will act on. > Essentially, the resulting *.pdf contains the lines output by the cat > function in basicplot. Or: > \begin{figure} > \includegraphics{scatter1.pdf} > \caption{myname} > \end{figure} > These lines are not in the environment acted by Latex. I tried a > variant of the function where <<results=tex,echo=FALSE>> and received > the same result. Below are the files *.Snw -> *.tex -> *.pdf and the > output I received while compiling. If there is anything else I can > give to help you help me just let me know. Thanks! > > MattMatt, I don't know if you have reviewed the Sweave manual, but section 3.4 provides insight into reusing named code chunks, as an alternative to looping or creating LaTeX macros as proposed by Dieter. These can be "nested" within other named code chunks and/or R code. If you don't yet have the manual, it is available here from Fritz' site: http://www.ci.tuwien.ac.at/~leisch/Sweave/Sweave-manual-20060104.pdf You could consider using a figure chunk, if the sole output is the plot and not text. That way you don't have to worry about explicitly cat()ing the figure related LaTeX markup as you are doing above. Thus, the LaTeX markup for things like captions will be in LaTeX sections of the .Rnw file and you can use \Sexpr{}'s to include derived scalar values. The preferred approach may be to an extent dependent upon whether your final document will simply have several plots on one or more pages in sequence, or whether you will need to have text between the plots, such that you really need LaTeX sections between the figure/code chunks. Back to Dieter's solution for a moment, take note of the Sweave FAQ (also in the above manual), specifically FAQ A.9, which covers the issue of figure chunks and multiple plots, proposing a looping approach consistent with Dieter's. I hope that this might give you some other insights into alternative approaches. HTH, Marc Schwartz