[Tex/LaTex] xtable function generated latex does not get parsed for special char such as square brackets

charactersknitrxtable

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?

Best Answer

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).
<to be read again> 
                   >
l.83   [3,4]
             & bleah \\
? 
! Emergency stop.
<to be read again> 
                   >
l.83   [3,4]
             & bleah \\
!  ==> Fatal error occurred, no output PDF file produced!
[....]

Note that if you might have other special characters that also need to be sanitized in your row names, you will have to also include that in your custom function as the default sanitization function is not used if you supply one.

Related Question