3

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?

  • 1
    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
3

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.

  • It worked!! This is exactly what I wanted. Thank you very much. – user2418594 Jul 12 '13 at 20:50
  • Another option is to function(x) gsub("[", "\\lbrack", x, fixed = TRUE) – MichaelChirico Sep 26 '15 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.