# xtable function generated latex does not get parsed for special char such as square brackets

I'm using the knitr package for putting my R output into PDF. I have two problems using xtable:

1. When my table data has chars like this: [, ] in them, the conversion from .tex to .pdf fails with error

2. When I use the package seqinr:stresc() to escape such chars, I'm able to get the content at least displayed (better than the situation 1 above). But remains the problem that the final PDF ends up displayed like this: \lbrack{}ABD\rbrack{} r22 instead of displayed like this: [ABD] r22.

Could anyone throw some light on how we can get this solved?

• Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. – karlkoeller Jul 12 '13 at 15:16
• Your question is far from clear but I would guess you have \\ [...] in which case the brackets are taken as an optional argument to \\  so use \\ {[...]} where the braces hide the square brackets. – David Carlisle Jul 12 '13 at 15:51

This can happen if your row names start with a left bracket, in which case you get the problem that David described in his comment. I've not seen it be a problem with brackets in the body of the table (but it may happen in some case). If that is what you are seeing, you can add a custom sanitize.rownames.function argument to the print.xtable function to wrap these in braces.

\documentclass{article}
\begin{document}

<<>>=
library("xtable")
DF <- data.frame(x=c("[]", "bleah", "foo[", "[", "]"),
stringsAsFactors = FALSE)
rownames(DF)[1:2] <- c("[1,2]", "[3,4]")
@

<<results="asis">>=
print(xtable(DF),
sanitize.rownames.function = function(x) paste0("{",x,"}"))
@

\end{document}


This .tex file generated from this (not shown) will give a valid PDF, where without the sanitize.rownames.function, it will give an error:

[....]
! Illegal unit of measure (pt inserted).
>
l.83   [3,4]
& bleah \\
?
! Emergency stop.

• Another option is to function(x) gsub("[", "\\lbrack", x, fixed = TRUE) – MichaelChirico Sep 26 '15 at 22:06