[Tex/LaTex] the best way to include R code in the Latex paragraph

rsourcecode

I am a newbie in Latex. I have two simple questions regarding including R code in Latex.

Q1: For a block of R code, I use 'listings' package, as follows.

\documentclass[12pt]{report}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=R]
> dpareto(4, 2, 3)
[1] 0.09375
> dpareto(4, -2, 3)
[1] NaN
> dpareto(seq(-1, 4, 1), 2, 3)
[1] 0.0000000 0.0000000 0.0000000 0.0000000 0.2962963 0.0937500
\end{lstlisting}
\end{document}

I feel it's not professional. What is the best way to present the block of R code?

Q2: For code pieces in the paragraph, for example I wish to include a R function, or variable, or package name in my Latex context, what is the best way to do that?

Best Answer

Better than list R code, you can make a my_sweave_file.Rnw file and compile it using knitr to execute the code, list it and show real results.

MWE3

\documentclass[a4paper]{article}
\parindent0pt
\begin{document}
Knitr test in \LaTeX.

<<Test>>= 

dpareto <- function(x, location, shape, log = FALSE) {
    if (!is.logical(log.arg <- log) || length(log) != 1)
        stop("bad input for argument 'log'")
    rm(log)

    L = max(length(x), length(location), length(shape)) 
    x = rep(x, length.out = L);
    location = rep(location, length.out = L);
    shape = rep(shape, length.out = L)

    logdensity = rep(log(0), length.out = L)
    xok = (x > location)
    logdensity[xok] = log(shape[xok]) + 
            shape[xok] * log(location[xok]) -
            (shape[xok]+1) * log(x[xok])
    if (log.arg) logdensity else exp(logdensity)
}

dpareto(4, 2, 3)
dpareto(4, -2, 3) 
dpareto(seq(-1, 4, 1), 2, 3)
@ 
Done. 
\end{document}

To compile this .Rnw file you can do:

Rscript -e "library(knitr); knit('my_sweave_file.Rnw')"
pdflatex my_sweave_file.tex

But with editors like RStudio or LyX you can compile this files directly.

Note that the listed R code of you MWE is confusing and not reproducible, as you do not explain where dpareto() come from, so. If you use the library PtProcess instead of the listed function above, the result will be ratter different:

MWE

\documentclass{article}
\parindent0pt
\begin{document}

Knitr test in \LaTeX.

{\footnotesize
<<Test, tidy=TRUE>>= 
library(PtProcess) 
dpareto(4, 2, 3)
dpareto(4, -2, 3) 
dpareto(seq(-1, 4, 1), 2, 3)
@ 
}

Done. The true first result is \Sexpr{dpareto(4, 2, 3)}, not 0.09375
as showed in the MWE.

\end{document}

Or with the library actuar:

MWE2