Quantcast
Viewing all articles
Browse latest Browse all 2

Answer by Fran for What is the best way to include R code in the Latex paragraph

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.

Image may be NSFW.
Clik here to view.
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:

Image may be NSFW.
Clik here to view.
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.09375as showed in the MWE.\end{document}

Or with the library actuar:

Image may be NSFW.
Clik here to view.
MWE2


Viewing all articles
Browse latest Browse all 2

Trending Articles