Search code examples
rknitrbeamer

How to format output of results using output hooks in knitr?


I have a Rnw file a.Rnw with the following contents:

\documentclass{beamer}
\begin{document}
\begin{frame}[fragile]
<<>>=
1+1
@
\end{frame}
\end{document}

I produce a pdf by

Rscript -e 'knitr::knit("a.Rnw")'
pdflatex a.tex

The output in a.pdf looks like this:

Output of knitr chunk

How do I get the output to look like this:

R> 1+1
## [1] 2

That is, how do I put R> in front of the R code and remove the blank line between code and output?


Solution

  • To show R> in front of all R commands, I set the R prompt using options and tell knitr to show the prompt using opts_chunk (code at bottom of answer).

    Getting rid of the new line is a bit trickier because the R code and R output in the generated tex file looks like this:

    \begin{alltt}
    \hlstd{R> }\hlnum{1}\hlopt{+}\hlnum{1}
    \end{alltt}
    \begin{verbatim}
    ## [1] 2
    \end{verbatim}
    

    So the newline between R code and its output is not generated explicitly by knitr, but is due to a new paragraph being started between \end{alltt} and \begin{verbatim}. The verbatim environment adds above and below it the current value of \topsep (see here). So I patch the knitrout environment such that this variable is locally set to 0pt. Here is the new version of a.Rnw:

    \documentclass{beamer}
    
    % reduce whitespace between R code and R output
    \let\oldknitrout\knitrout
    \renewenvironment{knitrout}{
      \begin{oldknitrout}
      \topsep=0pt
    }{
      \end{oldknitrout}
    }
    
    % show R> prompt before R commands
    <<r setup, echo=FALSE>>=
    options(prompt='R> ')
    knitr::opts_chunk$set(prompt=TRUE) 
    @
    
    \begin{document}
    \begin{frame}[fragile]
    <<>>=
    1+1
    @
    \end{frame}
    \end{document}
    

    and the output looks like this:

    pdf generated by knitr with reduced whitespace between R code and output