Adding Comments to R Code in Sweave - r

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!

Related

How to generate a plot and display it elsewhere in rnw file?

I saw this https://bookdown.org/yihui/rmarkdown-cookbook/fig-chunk.html and I'm wondering if there is something similar if a use a .rnw file that I compile in a pdf with knitr.
Thanks in advance for the help.
Yes, you can use the same trick. All you need to do is use the right syntax in your document, i.e., LaTeX in your case. Below is a translation of the example you mentioned from (R) Markdown to Rnw/LaTeX:
We generate a plot in this code chunk but do not show it:
<<cars-plot, dev='pdf', fig.show='hide'>>=
plot(cars)
#
After another paragraph, we introduce the plot:
\includegraphics{\Sexpr{knitr::fig_chunk('cars-plot', 'pdf')}}

R Sweave: put the whole code of the .Rnw file in Appendix?

I just found this awesome technique to put the code used in the .Rmd file in the appendix (of that same file).
However, I am using R Sweave and not R Markdown and I would like to know if there exists a similar way to put all the code at the end in a unique chunk. The code to do that in Markdown does not work in Sweave. I precise that, unlike this post, I do not have a separate .R file where the calculations are made. Everything is done in the .Rnw file.
Does anybody know how to do it?
Edit : a reproducible example
\documentclass[11pt, twocolumn]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\begin{document}
\SweaveOpts{concordance=TRUE}
<<reg2, echo=FALSE, print=FALSE>>=
head(mtcars)
#
<<reg3, echo=FALSE, print=FALSE>>=
head(iris)
#
\section*{Appendix}
% the place where I could like to put the whole code
\end{document}
This chunk works to include the code:
<<echo=FALSE, eval=TRUE>>=
filename <- tempfile(fileext=".R")
Stangle("test.Rnw", output = filename, quiet = TRUE)
cat(readLines(filename), sep = "\n")
#
When I include that in your example file, I see this:
I think it's possible to modify the format a bit; see ?Rtangle for some details. Similar things are possible with knitr, but it's more flexible. I suspect the best method would be similar to the one you found for RMarkdown.

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") ...

Getting Sweave code chunks inside some framed box?

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.

Hide entire part of document using Sweave condition

I would like to hide an entire part of my document including the LaTeX parts between code chunks.
The code might look like
<<echo=FALSE, results=tex>>=
if (showpart) {
#
Here we have quite a lot of latex, { that is not necessarily well-formed \end{itemize}
<<echo=FALSE, results=tex>>=
}
#
I already tried to insert \begin{comment} and \end{comment} using the verbatim package, but this does not cope well with the bad formed latex.
Any suggestions?
Thanks for your help.
You may try something like if (showpart) cat('\\begin{comment}'), then if (showpart) cat('\\end{comment}'), with the option results=tex. The point is you have to output valid LaTeX code from R.

Resources