[Tex/LaTex] Running R code from latex. (alternative to knitr)

knitrluatexr

If you want to export the output of an R script to latex and create a pdf document you can use the package Knitr with RStudio.
But I guess this is only a good practise for short results.

What if I want to create a whole book, a 1000 pages thesis?

How do yo do the opposite?

I mean, Can I include R code within my latex files and run it directly from say TexStudio+LaTex/LuaTex? (In order to get the numerical results and graphics in the pdf).

How?

NEW:
Some people said one can use knitr to generate big docuemnts.
Even if it's possible I think it's more comfortable and versatile to create LaTex documents from specific platform such as TexStudio.

So, what is the best practice?.
Mixing both methods?: Generating parts of the document with Knitr and later mixing and modifying them with TexStudio?. How?

There are packages like lstlisting designed to show code properly but not to run it.

Best Answer

In ConTeXt, you can use the filter module for such tasks. In fact, the filter module is a generalization of ConTeXt MkII module m-r, which was designed for specifically what you are asking.

However, with the filter module it is easy to replicate the functionality for any language, so there is no MkIV version of m-r.

Here is a minimal example:

\usemodule[filter]

\defineexternalfilter
  [R]
  [
     filtercommand={R CMD BATCH -q --save --restore \externalfilterinputfile\space \externalfilteroutputfile},
     output=\externalfilterbasefile.out,
     readcommand=\typefile,
     read=no,
     cache=yes,
   ]

\starttext
\startR
  ushape <- c(rexp(500000), 12-rexp(500000))
  pdf("ushape.pdf")
  par(mfrow=c(1,2))
  hist(ushape)
  plot(density(ushape), main="Density")
  dev.off()
\stopR

\startplacefigure[location=here, title={Output from R}]
  \externalfigure[ushape.pdf][height=0.5\textheight]
\stopplacefigure

\stoptext

which gives

enter image description here

Note that the files are cahced, so subsequent runs are very quick.