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

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.

Related

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!

Display .R script in output of .Rmd file

Is it possible to include or display an .r script in the output of .rmd file?
Important - just want to display the .r file!
Tried source(filename.r); source does not display it.
Any ideas?
**knitr Global Options**
```{r echo=TRUE}
knitr::opts_chunk$set(tidy=FALSE, fig.path='figures/')
```
**Load Libraries**
```{r echo=TRUE}
library(dplyr)
```
```{r echo=TRUE, include=TRUE}
source("external.R")
# the complete source code of the .r file should be displayed here
# possible?
```
What would be the use-case for such a requirement?
Creating .Rmd helps with documentation. In fact all my documentation is created using .Rmd.
There are .R scripts which take a long time to run (processing large data). In such a case working with .Rmd is not practical. Prefer to work with .R scripts.
If the source code of the .R can be "included & displayed" in the .Rmd would be wonderful for documentation purpose.
For this particular case, there is a simple solution. That is, you can assign source code to the chunk option code, then knitr will just take your source code as if it were written in the code chunk, e.g.
```{r, code = readLines('external.R')}
```
Alternatively and equivalently, you can use the file option:
```{r, file = 'external.R'}
```

Passing values from an Rnw file to an R script

Since I am a newbie as far as knitr is concerned, I am reading and modifying the examples given in knitr web site. One the approaches that caught my attention is to call chunks of an R script within an Rmw file. After compiling and modifying several examples, I wonder whether one can set a variable on an Rmw file and pass it to an R-script.
Here is an example
\documentclass{article}
\begin{document}
<<set-options, echo=FALSE, cache=FALSE>>=
options(replace.assign=TRUE)
opts_chunk$set(cache=TRUE, fig.show='asis')
read_chunk('simple_example.R')
#
\title{Example}
\author{Somebody}
\maketitle
\section{Print variable}
<<Print-data, echo=TRUE>>=
inp=2
#
\end{document}
and
# Simple Example
## ---- Print-data ----
inp=inp+2
print(inp)
The output result is ip=2 and an error msg "object inp not found".
Many thanks
The code chunk Print-data overrode the one in the Rnw file, so inp=2 was not executed, hence the error.
It seem you want to embed the chunk after Print-data:
<<>>=
inp=2
<<Print-data>>
#

Using R Markdown chunks in R Sweave(Knitr)

I have a R Markdown file that has my notes and chunks of code. I now want to write a R Sweave(Knitr) document to publish a paper using those chunks. I do not want to cut and paste the chunks, I rather call them directly. That way if I update the chunks, I don't have to do it in two places. It seems like it would be simple enough, but I can not figure it out. My code is as follows, test.rmd is my mark down document, foo is the chunk in the rmd file.
Test.rnw
<<Setup>>===
read_chunk('test.rmd')
#
<<foo>>==
#
Test.rmd
```{r foo, echo=TRUE}
print(summary(cars))
```
I would expect a summary of cars to be displayed in the output of the compilation of test.rnw into a PDF. But I don't. Any help is greatly appreciated.
read_chunk reads chunks from r script so call purl before read_chunk:
<<Setup>>=
knit_patterns$set(all_patterns[["md"]])
purl("test.Rmd")
knit_patterns$set(all_patterns[["rnw"]])
read_chunk("test.R")
#
<<foo>>=
#

Include latex tables generated by Hmisc latex in knitr slides

I am sorry, I am new to using knitr to make slides. I generally use the latex() function in Hmisc package to generate my tables based on R objects. I would like to produce a slide that shows the r code and then below it displays the properly formatted table. Something like:
``` {r}
latex(tabdat,file="tables/tabdat.tex",ctable=TRUE,caption="A basic table",caption.loc="bottom",label="tab:dat1",row.names=NULL,rowlabel="")
```
So that the finished slide displays the exact r code and the formatted table looking exactly as if I had run latex using \input{tabdat}
I would appreciate any advice on how to accomplish this.
Thanks!
I am a bit puzzled because you talk about PDF/LaTeX output but you are using R markdown tags.
Here are small examples for both cases, R Sweave, i.e. LaTeX output, and R markdown, i.e. HTML output. For creating the LaTeX code there are several packages available (xtable, Hmisc etc.) for HTML AFAIK only xtable.
The main point of how to include the raw output just like it appears in the console is the same for both output types and was already explained by Tyler Rinker above, i.e. by adding results="asis" to the chunk options.
PDF/LaTeX / Rnw-file
\documentclass{article}
\begin{document}
<<echo=FALSE, message=FALSE>>=
library(Hmisc)
library(xtable)
#
<<results='asis'>>=
latex(head(iris), file = '')
#
<<results='asis'>>=
xtable(head(iris))
#
\end{document}
HTML, Rmd-file
```{r echo=FALSE}
library(xtable)
```
```{r results='asis'}
tbl <- xtable(head(iris))
print(tbl, type="html")
```
Look here for more examples and options: http://www.stat.iastate.edu/centers/CCGS/slides/slides-Rtables.pdf

Resources