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
  • 2
    This is very, very well documented: \lstinputlisting
    – DG'
    Mar 23, 2019 at 9:43
  • @DG' - Thanks.And apologies for not looking for this first.
    – user81677
    Mar 23, 2019 at 9:54

1 Answer 1

5

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.

You must log in to answer this question.