%% LyX 2.2.1 created this file.  For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
\documentclass{article}
\usepackage[sc]{mathpazo}
\usepackage[T1]{fontenc}
\usepackage{geometry}
\geometry{verbose,tmargin=2.5cm,bmargin=2.5cm,lmargin=2.5cm,rmargin=2.5cm}
\usepackage{url}
\usepackage[unicode=true,pdfusetitle,
 bookmarks=true,bookmarksnumbered=true,bookmarksopen=true,bookmarksopenlevel=2,
 breaklinks=false,pdfborder={0 0 1},backref=false,colorlinks=false]
 {hyperref}
\hypersetup{
 pdfstartview={XYZ null null 1}}
\usepackage{breakurl}
\usepackage{listings}
\lstset{language=R}
\begin{document}
<<setup, include=FALSE, cache=FALSE>>=
library(knitr)
opts_chunk$set(fig.path = 'figure/listings-')
options(formatR.arrow = TRUE)
render_listings()
@

\title{Using listings with knitr}

\author{Yihui Xie}

\maketitle
To use the \textbf{listings} package with \textbf{knitr}, all you
need to do is to call a function in your first setup chunk (that chunk
should be hidden from the output with \texttt{include=FALSE} and should
not be cached):

% I just want to echo the 2nd line
<<setup, echo=2>>=
@

This function modifies the output hooks and header information so
that the output is written in \textbf{listings} environments, which
are kindly provided by Frank Harrell and can be found in \url{https://github.com/yihui/knitr/blob/master/inst/misc/Sweavel.sty}.
Of course you have to install the \textbf{listings} package if your
\LaTeX{} toolset does not include this package.

Now we can see how the results look like with our new settings:

<<boring-random>>=
set.seed(1121)  # for reproducibility
options(width=85)
x=rnorm(20)
x
mean(x)
sqrt(-1)  # this will give you a warning message
@

Another chunk:

<<rgl-hook-demo,eval=FALSE>>=
hook_rgl = function(before, options, envir) {
    ## after a chunk has been evaluated
    if (before || !require('rgl') || rgl.cur() == 0) return()  # no active device
    name = paste(valid_prefix(options$fig.path), options$label, sep = '')
    par3d(windowRect = 100 + options$dpi * c(0, 0, options$width, options$height))
    Sys.sleep(.05) # need time to respond to window size change

    fmt = opts_knit$get('out.format')
    if (fmt %in% c('html', 'markdown', 'gfm', 'jekyll')) options$dev = 'png'

    ## support 3 formats: eps, pdf and png (default)
    switch(options$dev,
           postscript = rgl.postscript(paste(name, '.eps', sep = ''), fmt = 'eps'),
           pdf = rgl.postscript(paste(name, '.pdf', sep = ''), fmt = 'pdf'),
           rgl.snapshot(paste(name, '.png', sep = ''), fmt = 'png'))

    if (fmt == 'html') return(.plot.hook.html(c(name, 'png'), options))
    if (fmt %in% c('markdown', 'gfm', 'jekyll'))
        return(.plot.hook.markdown(c(name, 'png'), options))

    paste(ifelse(options$align == 'center', '\\centering{}', ''), '\\includegraphics[',
          sprintf('width=%s', options$out.width), ']{', name, '}\n', sep = '')
}
@

Well, we can do crazier things with \textbf{knitr}. Here we use the
\texttt{fig.cap} option to write plots into the \texttt{figure} environment
automatically, and the caption is generated from data dynamically
(see Figure \ref{fig:boxplot-ex}):

% set an option first
<<eval-opts, echo=FALSE>>=
opts_knit$set(eval.after = 'fig.cap') # evaluate fig.cap after the chunk

<<boxplot-ex, fig.height=2, out.width='.8\\linewidth', fig.cap=sprintf('This is a boxplot; the median is %.2f.', median(x))>>=
par(mar=c(4,4,.1,.1))
boxplot(x, horizontal=TRUE)
@

As we know, \texttt{figure} is a float environment, so it has floated
away from the R code to the top of this page. This should not be surprising
to \LaTeX{} users.

You should be able to compile the \TeX{} document and get a PDF file
like this one: \url{https://github.com/yihui/knitr/releases/download/doc/knitr-listings.pdf}.
For more information about out hooks, see \url{https://yihui.name/knitr/hooks}.
\end{document}
