Reputation: 661
I am trying to output the freq table generated by cut
to a PDF file using knitr and xtable. However, when I include the option include.rownames=FALSE
the output is not processed and an error is reported whereas the code works with include.rownames=TRUE
. Test code is below:
\documentclass[12pt]{article}
\begin{document}
<<test_table, results = "asis",echo=FALSE>>=
library(xtable)
x <- sample(10,100,replace=TRUE)
breaks <- c(1,2,5,10)
x.freq <- data.frame(table(cut(x, breaks, right=FALSE)))
print(xtable(x.freq),include.rownames=TRUE)
@
\end{document}
When I use include.rownames=TRUE
I get the output below.
1 [1,2) 5
2 [2,5) 35
3 [5,10) 49
whereas when I use include.rownames=FALSE
I get an error:
Test.tex:71: LaTeX Error: \begin{tabular} on input line 58 ended by \end{document}.
I believe that I am getting the error because of the presence of the square braces ' [ ' in the text source.
Does anyone know how to solve this problem?
Upvotes: 2
Views: 1060
Reputation: 37814
The problem is that the end of each row in the table is a \\
which has an optional argument to specify how much space to leave before the next row, for example, \\[1in]
. There's allowed to be white space between the \\
and the [
, so in this case, it's trying to read the [2,5)
as that argument.
A simple workaround would be to change the labels of the factor to include some non-printing blank character first, however, if you do so, by default, print.xtable
will "sanitize" it so that it actually does print, so you'd need to turn that off by passing a new sanitize function; identity
will do none of this fixing.
levels(x.freq$Var1) <- paste0("{}", levels(x.freq$Var1))
print(xtable(x.freq),include.rownames=FALSE, sanitize.text=identity)
Upvotes: 5