bretauv
bretauv

Reputation: 8557

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}

Upvotes: 0

Views: 413

Answers (1)

user2554330
user2554330

Reputation: 44867

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:

screenshot

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.

Upvotes: 1

Related Questions