[Tex/LaTex] Creating Bold Column Headers using xtable (knitr)

knitrxtable

what is the easiest way to bold all column headers using the output of calling xtable, ideally under the print.xtable command. I am using knitr.

Best Answer

Example

\documentclass[a5paper]{article}
\usepackage{booktabs,colortbl,xcolor}
\begin{document}

A simple raw \texttt{xtable}: 

<<before,results='asis',echo=F>>=
library(xtable)
df <- data.frame(
  One=c(101.000,22.345),
  Two=c(3.45,74.34),
  Three=c(65,6.1234))
print(xtable(df))
@

The same table with some formatting:

<<after,results='asis', echo=F>>=
bold <- function(x) {paste('{\\textbf{',x,'}}', sep ='')}
gray <- function(x) {paste('{\\textcolor{gray}{',x,'}}', sep ='')}
print(xtable(df,digits=0), 
      sanitize.rownames.function=gray, 
      sanitize.colnames.function=bold, 
      booktabs=T)
@
\end{document}