Exclude comment lines with chunk title and options with purl - r

When I purl() a .Rnw or .Rmd file, the resulting .R file has a commented line for each chunk that includes the chunk title and options for that particular chunk. I would like to distribute the .R file for a lecture, and think the extra lines, particularly the chunk options, are distracting for students. For example the chunk:
<<my_chunk, eval=FALSE>>=
x <- 1 + 2
#
ends up looking like:
## ----my_chunk, eval=FALSE------------------------------------------------
x <- 1 + 2
in the purled file. I would like to completely eliminate the commented line, or at the very least, the chunk options (i.e., eval=FALSE). What is the most straightforward way to do that? I did not have this issue with a previous version of knitr.

Related

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.

R chunk within markdown extension

I am trying to write a markdown document where I have a chunk of R code within a theorem or example extension.
I assumed I could simply write the theorem extension, starting and ending with ``` and within define an R code chunk starting with ```{r} and ending with ```. As follows:
```{theorem, name="Test"}
Some initial text.
```{r}
a <- 1 + 1
print(a)
And some more text.
However, it seems markdown gets confused, as does stackoverflow, by closing the theorem chunk using the end of the R code block instead of nesting the blocks. Any ideas on how to solve this?
You can't nest chunks like that in r-markdown. You'll need to close your first chunk then open a new one for the R chunk.

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>>=
#

Show code in appendix using knitr

I have an Rnw file (a large one) and I want to show all code used in an appendix.
It is suggested in some of the knitr examples (https://github.com/yihui/knitr-examples/blob/master/073-code-appendix.Rnw, also a good MWE) that having a code block like this is the way:
<<Rcode, eval=FALSE, ref.label=all_labels()[-1],echo=TRUE, cache=FALSE>>=
#
This works fine except all the code chunks merge into each other and none are labelled.
On the other hand if I run purl(myfile.Rnw) it labels the code chunks and separates them by two lines, which makes things much easier to read.
Is there any way of automatically listing the code using the second approach in a report appendix? I know I can have a code chunk to run purl to produce myfile.R as part of my report, but how do I then show the code in myfile.R in my appendix?
Here's an example .Rnw file (called "example.rnw"):
\documentclass{article}
\begin{document}
<<a>>=
x <- 1:10
x
#
<<b>>=
y <- 10:1
y
#
<<c>>=
z <- 1:5
z
#
\clearpage
\input{example-purl.tex}
\end{document}
If you create a file in your working directory called "template.rnw" that just contains:
<<%sCHUNK_LABEL_HERE, eval=FALSE>>=
#
Then, you run:
stitch(purl("example.rnw",output="example-purl.r"),template="template.rnw")
knit("example.rnw")
Does that make sense? Basically, you're purling, stitching the purled code, knitting the original document, and then compiling the resulting LaTeX ("example.tex") that includes the knitting and purling. Everything should be formatted nicely (and consistently).

Pass underscore in knitr R code

I need to call a database that has underscores in the table names in an R chunk in knitr. There are a couple thousand table names, and changing the names would be a huge hassle.
Something like:
<<classRun,fig=FALSE,print=FALSE,echo=FALSE>>=
getdat = function(nbr1,nbr2){
library(RODBC)
database.dsn1<-c("db")
database.user1<-c("username")
database.password1<-c("password")
channel<-odbcConnect(database.dsn1, database.user1, database.password1)
dat = sqlQuery(channel,paste("select * from table_",nbr1,"_",nbr2, sep=""))
}
#
<< results='asis', echo = FALSE>>=
dat = getdat(10,20)
print(dat)
#
I get the error that I am missing a $ ("Missing $ inserted") because of the underscore in "table_10_20". I have played around a lot with adding in '\$\', and '\$\', you name it. Also played around with cat(), and paste(), and single quotes, and double quotes. Any suggestions? Thanks in advance for your help. I am running Ubuntu 11.10, and calling knitr from RStudio with pdfLaTeX, if that matters.
Chances are you have a column name with an underscore in it.
Recall that results='asis' just dumps all the output as-is into the tex document.
For example, this is a reproducible example of your problem:
% test.Rnw
\documentclass[a4paper]{article}
\begin{document}
<<classRun, fig=FALSE, print=FALSE, echo=FALSE>>=
table_10_20 <- data.frame(col_1=1:10, col_2=runif(10))
#
<<results='asis', echo=F>>=
print(table_10_20)
#
\end{document}
If I run this through knitr I get the "Missing $ inserted".
If I look at the .tex file that gets produced, I see:
% test.Rnw
\documentclass[a4paper]{article}
.... lots of tex ....
\begin{document}
col_1 col_2
1 1 0.69699
2 2 0.12988
3 3 0.19662
4 4 0.04299
5 5 0.08750
6 6 0.72969
7 7 0.19818
8 8 0.27855
9 9 0.81806
10 10 0.56135
\end{document}
See how the column names col_1 and col_2 are just dumped as-is into the file? Well, in LaTeX an underscore has a special meaning (subscript), which is only valid in maths mode, hence the LaTeX compiler tries to put the maths mode delimiters ($) around the word, giving your error.
In your case, you have a few options depending on what you want for your output.
Use \begin{verbatim} with results='asis' to protect the underscores. This will dump your output into a verbatim environment.
\begin{verbatim}
<<results='asis', echo=F>>=
print(table_10_20)
#
\end{verbatim}
Use results='markup': this is like a verbatim environment except sweave colours the output. By default it'll put a comment mark (##) in front of every line; to remove this use comment=NA. (You can't see too well how this pic is different from the above; it is the same except it has a grey background to distinguish it from the rest of the document. It's the same markup as when you use echo=T).
<<results='markup', comment=NA, echo=F>>=
print(table_10_20)
#
The above two simply print your table as-is in fixed with font. If you want a proper latex table, you can use a package like xtable, which can convert a data.frame (& similar) ino proper LaTeX (or HTML) markup. I think there are other packages that can do this too but for the moment they escape me. You use results='asis' here. (See the documentation for more details, you really can control every aspect of what gets printed in the table and how):
<<results='asis', echo=F>>=
library(xtable)
print(xtable(table_10_20), include.rownames=FALSE)
#

Resources