1
votes

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!

1
I think you need to clarify what you mean by "next to each other". Do you want a small section of page in two columns, with R code in one column and LaTeX next to it?Gregor Thomas
Also, I think you should not call these "comments". Comments are what you would add in the R code with the # comment character. It sounds like you don't want comments, you want standard LaTeX (the content of which may or may not be to comment on the R code as you wish).Gregor Thomas
That said, if your main concern is "so that they are easily recognizable as comments", you should just use regular R comments in your code chunk and let syntax highlighting change the color so that they stand out. You can do it this way with Sweave, or it will be done by default if you switch to knitr.Gregor Thomas
@Llarian, does my answer help, or did I miss something?Auden Young
@ Gregor: Yes, I would like two different columns, it that is possible. The left columns should contain R code which is easily recognizable as such. The right column should present remarks to specific code lines, which are formatted like the main text. If that cannot be done, I could choose the solution via knitr that you pointed out; thanks for that.Llarian

1 Answers

0
votes

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

enter image description here

at the top of the page.

Hope this helps!