1

Is there a way to import an entire RScript (.R) file into Latex directly without manually using listings and copying the code into Latex?

  • 2
    This is very, very well documented: \lstinputlisting – DG' Mar 23 at 9:43
  • @DG' - Thanks.And apologies for not looking for this first. – Adeetya Mar 23 at 9:54
3

foo.R:

# ---- foo

bah <- data.frame(a=c(1,2,3),b=c(4,5,6))
library(xtable)
print(
        xtable(bah,
                cap="My data frame",
                label="footable"),
        table.placement="!b",
        booktabs = T)
plot(bah$a,bah$b)
a <- mean(bah$a)
b <- mean(bah$b)

Note: The # ---- foo is not only a comment. It is a must label, as is.

foo.Rnw:

\documentclass[twocolumn]{article}
\setcounter{totalnumber}{40}
\setcounter{bottomnumber}{20}
\usepackage{booktabs,parskip,lipsum}
\usepackage[colorlinks,linkcolor=blue]{hyperref}
\pagestyle{empty}
\begin{document}

<<external-code,echo=FALSE>>=
read_chunk('foo.R')
@

\section*{R code}

<<foo,eval=FALSE,echo=TRUE>>=
@

\section*{output}

<<foo,eval=TRUE,echo=FALSE,results='asis',fig.cap="My plot", fig.height=3,fig.pos="!b">>= 
@

The R code produces the mean of \verb|a|, that is \Sexpr{a},  
and the mean of \verb|b|=\Sexpr{b}, and the table \ref{footable} 
with data frame and the figure \ref{fig:foo} with scatterplot 
of \verb|a| {\em versus} \verb|b|.

\lipsum[1-8] % dummy text

\end{document}

foo.pdf, page 1:

mwe

Note: If you have no idea of how compile this, or what the hell is knitr, just load foo.Rnw in the Rstudio editor a push the "Compile PDF" button, and of course, search information about knitr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.