Stéphane Laurent
Stéphane Laurent

Reputation: 84529

LaTeX math expression in knitr kable (Sweave)

Is it possible and how to use a LaTeX math expression in a knitr/Sweave report with kable? In the example below, $x^2$ is rendered "as is".

With xtable, for the example below, I would use the option sanitize.colnames.function = function(x) x of print.xtable. Is there such an option for kable?

\documentclass{article}
\usepackage{booktabs}
\begin{document}

<<>>=
library(knitr)
dat <- mtcars[1:5,1:5]
options(knitr.table.format = "latex")
@

<<results='asis'>>=
names(dat)[1] <- "$x^2$"
kable(dat, booktabs=TRUE, caption="My table")
@

\end{document}

enter image description here

Upvotes: 17

Views: 6149

Answers (2)

Luis Aguilar
Luis Aguilar

Reputation: 1

Yes, use this:

names(dat)[1] <- "$x^{2}$"

this might also help you sometime:

names(df) <- c("$\\lambda_1$", "$\\lambda_2$","$\\lambda_3$" )

the result is the same of:

names(df) <- c("$λ_{1}$", "$λ_{2}$", "$λ_{3}$")

Upvotes: 0

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

Yes, use the option escape=FALSE:

kable(dat, booktabs = TRUE, caption = "My table", escape = FALSE)

Upvotes: 20

Related Questions