knitr sanitises the % marker for LaTex comments and they show up in the final document

Thanks to @Tyler, I went browsing the knitr issues page and learned that xtable has an argument to suppress the comments (upvote to Tyler for that). It is a bit hard to use because you have to pass the argument to xtable's print method. The code that solves my problem looks like:

print(xtable(table,include.colnames=TRUE),comment=FALSE)


We can resolve this permanently by setting an xtable option:

options(xtable.comment = FALSE)

See ?print.xtable; since the comment argument defaults to getOption("xtable.comment", TRUE), any calls to print.xtable will thereafter exclude the comment. Much credit due to mnel on SO for suggesting to do it permanently.


This is an xtable issue: xtable is designed for use within a LaTeX source document, and when you try to use it in a Markdown document instead, the formatting of comments becomes difficult to control as it passes from Md -> pandoc -> LaTeX -> pdf. There is some discussion on the knitr issues page. Knitr now includes the function kable to deal with simple tables. Alternatively, you could use a wrapper to strip the comments from xtable:

tyxtable <- function(x, trim = 2) {
    tmp <- textConnection(capture.output(xtable(x), file = NULL))
    tmp <- readLines(tmp)
    tmp <- tmp[-1:(-1 * trim)]
    writeLines(tmp)
}

Tags:

R

Xtable

Knitr