Pass underscore in knitr R code - r

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

Related

Exclude comment lines with chunk title and options with purl

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.

R, knitr doesn't respect order of chunks and text

Imagine I knit this Rnw file:
\documentclass{article}
\begin{document}
Table1
<<example,results='asis', echo=FALSE>>=
require(xtable)
nn <- 15
mydata <- data.frame(A=1:nn,C=nn:1, C=runif(nn), D=rnorm(nn))
xtable(mydata, caption="Table1")
#
Table2
<<example2,results='asis', echo=FALSE>>=
xtable(mydata, caption="Table2")
#
Table3
<<example3,results='asis', echo=FALSE>>=
xtable(mydata, caption="Table3")
#
\begin{obeylines}
Just some text
\end{obeylines}
\end{document}
It's a simple example that just prints some text and three tables.
Strangely it doesn't respect the order of what I've written on my code.
I get this (sideview of the two pdf pages)
But "Table3" text should appear before the table3 itself and after table2, and the text "just some text" should appear at the very end of the document.
If I write several lines there it breaks the lines.
I understand that if a table doesn't fit on a place it must be moved to the next page but so should be done with the following text and tables.
I've also observed that in other examples some tables are reallocated randomly when they don't fit well.
How can I prevent knitr from doing this?
I don't know whether is a knitr problem or latex.
I'm using Texlive 2015, Rstudio, R 3.2.3 and Windows 10 and the latest version of all packages involved.
By default print.xtable() produces a LaTeX \table{...} environment, which is defined as a floating object. See `?print.xtable and try e.g.
<<example2,results='asis', echo=FALSE>>=
print(xtable(mydata, caption="Table2"),floating=FALSE)
#
(untested ...)
alternatively you could try table.placement="H"; you may need \usepackage{float} (see this question from tex.stackexchange.com).
(also untested ...)

Knitr: Trailing zeros on inline text

I am currently having trouble achieving the desired rounding of numbers using knitr. The issue occurs with numbers that would end with a zero on the final rounded digit. An example of this is 14.04, which I want to be rounded at 1 decimal place to 14.0. The issue is that knitr with latex as the output gives 14 without the 0 as the decimal place.
I would assume that there is some sort of trailing zero option, but I cannot locate it. Any ideas? Bellow is a short minimal working example of the issue.
\documentclass[12pt]{article}
\begin{document}
<<>>=
library(knitr)
options(digits=1)
#
Full number = 14.0417
Number of issue \Sexpr{14.041783}
Should appear as 14.0
\end{document}
EDIT: While looking at the first answer (Thanks for the rapid reply Ben), I realised the other issue that I have here. While solutions where the number is formatted as a string, get around the main issue, they do not solve the same issue when it occurs on "large" numbers, which become formatted using scientific notation.
I will give a second example that demonstrates this: say the number is 100,400,000. The resulting output using options(digits=2) becomes 10^8, where I would prefer 1.04 x 10^8. Rnw example below.
\documentclass[12pt]{article}
\begin{document}
<<>>=
library(knitr)
options(digits=2)
#
Number 100,400,000
\Sexpr{100400000}
\end{document}
I think this answers it: use sprintf().
\documentclass[12pt]{article}
\begin{document}
<<>>=
library(knitr)
options(digits=1)
x <- 14.0417
#
Full number = \Sexpr{x}
Number of issue \Sexpr{sprintf("%.1f",x)}
\end{document}

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

Sweave: interpret R's output as LaTeX code

I have written some custom R code that wraps a third-party binary. One of that binary's features is to produce a LaTeX document with a figure and some text. One of my code's features is to parse that document and return the LaTeX code for the figure.
The goal is to embed my R code in an Rnw document. When Sweave is run, I want my code to produce a document using the third-party binary, then extract the LaTeX code for the figure and drop it into Sweave's .tex output. Then when I run latex against that output the figure that was generated by the third-party binary should appear, automagically and nicely formatted, in my report.
Instead, the LaTeX code is printed out like this:
[1] " %\\begin{landscape}"
[1] " \\begin{center}"
[1] "\\psset{linecolor=black,tnsep=2pt,tnheight=0cm,treesep=.3cm,levelsep=40pt,radius[1] "% \\def\\psedge#1#2{\\ncangle{#2}{#1}}"
[1] "% \\pstree[treemode=R]"
[1] " \\pstree{\\Tcircle{ 1 }~[tnpos=l]{\\shortstack[r]{nwsprec\\\\$\\leq$ 1.93}}}{"
And so on...
Is there a way to make Sweave treat R's output as LaTeX code?
Thanks in advance.
-Wesley
I figured it out! The Sweave code needs to look like this:
<<echo=False, results=tex, include=True>>=
...R code goes here...
#
Where the option results=tex is the crucial change that tells Sweave to interpret the output from R as LaTeX code.
And to get rid of the quotes and line numbers, I needed to use cat command in R rather than print. Specifically, I changed print(line) to cat( paste(line, "\n", sep='') ).

Resources