Getting Sweave code chunks inside some framed box? - r

I would like to make an R code chunk (in Sweave) printed inside a framed box in the resulting pdf.
Is there an easy solution for doing that?

The short answer is that yes, there is an easy way. Just add the following lines, or something like them to the preamble of your Sweave document:
\DefineVerbatimEnvironment{Sinput}{Verbatim} {xleftmargin=2em,
frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{xleftmargin=2em,
frame=single}
This works because the appearance of code (and output) chunks is controlled by the definition of the Sinput and Soutput environments. These are both Verbatim environments as provided by the LaTeX package fancyvrb. (Click here for a 73 page pdf describing the numerous options that fancyvrb provides).
A quick look in the file Sweave.sty reveals the default definition of those two environments:
\DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{}
\DefineVerbatimEnvironment{Scode}{Verbatim}{fontshape=sl}
To change those definitions, just add \DefineVerbatimEnvironment statements of your own devising either: (a) at the end of the Sweave.sty file; or (b) at the start of your *.Snw document.
Finally, here's an example to show what this looks like in practice:
\documentclass[a4paper]{article}
\usepackage{Sweave}
\DefineVerbatimEnvironment{Sinput}{Verbatim} {xleftmargin=2em,
frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{xleftmargin=2em,
frame=single}
\title{Sweave with boxes}
\begin{document}
\maketitle
<<echo=FALSE>>=
options(width=60)
#
Here is an example of a code chunk followed by an output chunk,
both enclosed in boxes.
<<>>=
print(rnorm(99))
#
\end{document}

knitr, a successor of Sweave, by default outputs all echoed R code in boxes, and also formats it to the margins. Other nice features include syntax coloring and PGF integration.
Sweave code of average complexity needs only minor if any adaptions to run with knitr.

Related

knitr: automate producing multiple versions of PDF for beamer slides

For lectures, I am using knitr to produce LaTeX beamer slides as a PDF. For a given lecture, I want to produce also (a) 1-up handout (using the handout option, and (b) the same handout formatted 4-up.
I find I have to run knitr 3 times to do this as shown below. Is there a way to simplify this work flow?
A lecture stub:
\documentclass[10pt,table]{beamer}
\input{inputs/beamer-setup}
\input{inputs/defs}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
...
\end{document}
And I run knitr as
knit2pdf("Lecture1.Rnw")
To get the 1-up handout (which suppresses the separate pages when you use transitions), I edit the first line to:
\documentclass[10pt,table,handout]{beamer}
and run
knit2pdf("Lecture1.Rnw" output="Lecture1-1up.tex")
Finally, to get the 2 x 2 version, I use the LaTeX pgfpages package,
\documentclass[10pt,table,handout]{beamer}
\input{inputs/beamer-setup}
\input{inputs/defs}
\usepackage{pgfpages}
\pgfpagesuselayout{4 on 1}[letterpaper,landscape]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
And run:
knit2pdf("Lecture1.Rnw" output="Lecture1-4up.tex")
(I found that with beamer, I could not simply print the PDF 4-up using Adobe Acrobat -- it generated a corrupt PDF file. I was forced to use pgfpages)
Then, of course I have to revert my .Rnw file to the original if I need re-do the slides. Very tedious. There must be a better way.

pandoc skip latex environment

I'm writing mainly in LaTeX, but some co-authors prefer MS Word. To facilitate their work a bit, I would like to convert the .tex file (or the .pdf) to a .docx. The formatting does not need to be perfect, but all of the text, equations, figures etc should be perfectly readable.
I'm currently thinking to take the .tex document, replace all the essential stuff and then let Pandoc do it's magic. For this I would preferably implement my additions as a Pandoc filter. E.g., my tikz pictures would be converted to png using the tikz.py filter provided with Pandoc. The problem I'm facing with this approach is that Pandoc tries to interpret the tikz environment upon conversion from tex into it's internal language and the filters take this internal language as an input. The result is that the tikz code is lost. Is there a way to tell Pandoc to leave any tikzpicture environments alone?
Edit:
See the MWE below:
MWE.tex contents:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw (0,0) -- (2,2);
\end{tikzpicture}
\end{document}
Output of pandoc -t native MWE.tex
[Para [Str "(0,0)",Space,Str "\8211",Space,Str "(2,2);"]]
The \draw command has completely disappeared as you can see.
I found that pandoc does not skip code encapsulated in \iffalse ... \fi, so you can redefine the tikpicture environment as such (or in any other way you might like):
\documentclass{article}
\usepackage{tikz}
\iffalse
\renewenvironment{tikzpicture}%
{\par---start tikzpicture---\\}%
{\\---end tikzpicture---\par}
\renewcommand{\node}{node:}
\fi
\begin{document}
\begin{tikzpicture}
\node {foo};
\end{tikzpicture}
\end{document}
With pandoc 2.5 this results in a docx file containing:
—start tikzpicture—
node:foo;
—end tikzpicture—
This feels very wrong, and I wish I knew a nicer way.

Adding Comments to R Code in Sweave

I am working on a document about R software, which is currently stored in a Rnw file to eventually process it with Sweave. The document contains several R code chunks, of the usual form:
<<>>=
R Code
#
Next to some code lines, I would like to add specific comments, which I would like to be displayed like usual LaTeX text (so that they are easily recognizable as comments). Is there a way to display R code chunks and corresponding comments next to each other when using sweave or knitR?
Thank you for your help!
If you want the to be formatted like code (I assume that is what you mean) you can use the following code:
\begin{filecontents*}{my_r_code_test.r}
R code
#
|\includegraphics[width=0.5\textwidth]{example-image}|
\end{filecontents*}
\documentclass{article}
\usepackage{xcolor}
\usepackage{graphicx}
\usepackage{listings,mdframed}
\lstset{
language=R,
backgroundcolor=\color{black!5}, % set backgroundcolor
basicstyle=\footnotesize\ttfamily,% basic font setting
columns=fullflexible,
}
\begin{document}
\begin{mdframed}[backgroundcolor=black!5,linewidth=0pt,%
innerleftmargin=0pt,innertopmargin=0pt,innerbottommargin=0pt]
\lstinputlisting[escapeinside=||]{my_r_code_test.r}
\end{mdframed}
\end{document}
Which produces
at the top of the page.
Hope this helps!

Can I use a knitr inline expression in the title of a latex document?

I'd like to use a Knitr/Sweave in-line call (\Sexpr{}) in the title of a LaTeX document, after the \begin{document} command but before the \maketitle command. The in-line R code would extract one or two pieces of information from an R data-frame created early in the R script I'm embedding in LaTeX.
I have a couple of Knitr chunks that create a data.frame from which I derive the information I want to put in the Title. I've tried placing these chunks between LaTeX's \begin{document} call and the \title code, like this:
\documentclass
[LaTex Preamble]
\begin{document}
[%% Knitr chunks that initialize an R data-frame]
\title \Sexpr{--a snippet of R code that extracts an element from the data-frame --}
\maketitle
... (rest of the LaTeX document)
and I've also tried putting the Knitr chunks in the preamble to the LaTeX code before \begin{document} statement.
But in Knitr seems to ignore code (other than initialization) that is placed ahead of the \maketitle call in LaTeX, so the in-line snippets included the title look like errors to Latex and it halts output.
I can't find any information in the Knitr documentation on including in-line code in the Title of a LaTeX document.
Any ideas?
OK: Found the solution thanks to the hint from #ben-bolker below. Ben uses the formatting of R chunks before output to an RNW file (in a 2-step Knitr process: latex -> rnw -> pdf) . But I'm compiling the LaTeX file to PDF in one-step without going to an RNW file from inside TeXShop (on Mac OSX). I found that I could get Ben's example to work using the RNW delimiters (<<>>=) and one-step compiling. But I couldn't mix the usual LaTeX chunk-delimiters (%%begin.rcode and %% end.rcode) and the RNW in-line statement hook (\Sexpr{}). The latter didn't work no matter how I fiddled with it. Eventually I found that the correct in-line hook for LaTeX is \\rinline{}.
It's not very clear in the Knitr documentation that this is the required format for LaTeX and I found it eventually mainly thanks to Ben's example. Best, Peter
Update 2 ... and then there's RTFM (or the 'cheat sheet' in this case): http://cran.r-project.org/web/packages/knitr/vignettes/knitr-refcard.pdf
Hmm. The following file works for me:
\documentclass{article}
<<echo=FALSE>>=
x <- 5
#
\title{The number is \Sexpr{x^2}}
\begin{document}
\maketitle
Some stuff
\end{document}
with knitr version 0.8 on Ubuntu 10.04, via knit2pdf("knitr_title.Rnw") ...

figure* environment in twocolumn knitr/Sweave document

Sounds like it should be a common problem, but I didn't find an obvious trick.
Consider the knitr Rnw file below,
\documentclass[twocolumn, 12pt]{article}
\usepackage{graphicx}
\begin{document}
%\SweaveOpts{dev=pdf, fig.align=center}
\begin{figure*}
<<aaa, fig.width=8, fig.height=5, fig.show=hold>>=
plot(1,1)
#
\end{figure*}
\end{document}
I would like this wide figure to span two columns, using a {figure*} LaTeX environment. Is there a hook for that?
EDIT: wrapping the chunk in figure* gives the following output.
Two facts:
knitr makes everything accessible for you, so LaTeX tricks are often unnecessary;
there is a chunk hook with which you can wrap your chunk results;
A simple-minded solutions is:
knit_hooks$set(chunk = function(x, options) {
sprintf('\\begin{figure*}\n%s\n\\end{figure*}', x)
})
I leave the rest of work to you to take care of more details in options (e.g. when options$fig.keep == 'none', you should not wrap the output in figure*). You may want to see how the default chunk hook for LaTeX is defined in knitr to know better how the chunk hook works.
However, in this case, I tend to write the LaTeX code by myself in the document instead of automatically creating it. After you have got figure*, you may start to think about \caption{} and \label{} (not hard, but I still want to see them in LaTeX).
Not sure about how knitr but for Sweave (and basic latex) there is in fact a trick: have the R code produce a pdf file, and then use standard \includegraphics to pull it in.
So with this:
\documentclass[twocolumn, 12pt]{article}
\usepackage{graphicx}
\begin{document}
%\SweaveOpts{dev=pdf}
<<aaa,fig=FALSE,print=FALSE,echo=FALSE>>=
pdf("mychart.pdf", width=6, height=3)
set.seed(42)
plot(cumsum(rnorm(100)), type='l', main="yet another random walk")
invisible(dev.off())
#
\begin{figure*}
\includegraphics{mychart.pdf}
\end{figure*}
\end{document}
I got the document below (which I then converted from pdf to png):
I also had a similar problem while preparing a figure that should span two columns in a IEEE two-column conference paper.
Setting the chunk hook caused some strange error in my setup.
Even this simple hook: knit_hooks$set(chunk = function(x, options) x)
But after looking into knitr::opts_chunk$get(), I realized that simply setting fig.env="figure*" solves the problem in an elegant way.
Here is how my chunk looks like in an Rnw file:
<<fig1, fig.width=18, fig.height=6, fig.env="figure*">>=
#

Resources