[R] Insert R code in LaTeX document

Marc Schwartz MSchwartz at mn.rr.com
Sun Sep 17 17:30:47 CEST 2006


On Sun, 2006-09-17 at 16:45 +0200, Alexandre Depire wrote:
> Hello,
> i would like to insert R code in LaTeX document.
> I see something about the 'listings' package, but i would like if it is the
> best way and if it is possible to use the command \include{programme.R}.
> I have the following solution but it doesn't work with \include and \input
> 
> ======
> LaTex
> ======
> 
> main.tex
> ------------------
> \documentclass{report}
> \usepackage{listings}
> \lstloadlanguages{R}
> 
> \begin{document}
> \include{annexe}
> \end{document}
> 
> annexe.tex
> ---------------
> The code is:
> \lstset{language=R}
> 
> #\include{} or  \input or direct code ???
> 
> R code
> ========
> # test
> rm(list=ls())
> x<-1:10
> mean(x)

Depending upon how much functionality you actually need, using the
'verbatim' environment may be easier:

\begin{verbatim}
  R Code Here
\end{verbatim}

Then you don't need the rest of the LaTeX packages and associated code.
The verbatim environment will use a monospace font by default. It is
available by default in LaTeX, but you can also load the verbatim
package (\usepackage{verbatim}) for a better implementation. The
verbatim environment also provides a \verbatiminput{FileName} command
that will enable you to insert a text file that will automatically be
put in a verbatim environment:

  \verbatiminput{FileName.R}

The listings package provides a lot of other functionality such as
syntax highlighting, line numbers and so forth. I presume, given what
you have above, that you have already looked at the manual for the
package. If not and you are mimicking some online examples, then you
might want to review it:

ftp://indian.cse.msu.edu/pub/mirrors/CTAN/macros/latex/contrib/listings/listings-1.3.pdf

In either case, if you have an external file, you don't want to use
\include, as that is for .tex files specifically. The file argument is
the base name of the file only, without the extension and .tex is
presumed.

Thus, you want to use \input, where you can specify the full FileName.R
as the argument:
  
  \input{FileName.R}

If you just have a small amount of R code to include, then just put it
in the body of your main .tex file and you don't have to worry about
multiple files or using \input, etc.

HTH,

Marc Schwartz



More information about the R-help mailing list