# Using the booktabs package with Sweave and xtable

**cameron.bracken.bz » R**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The xtable package in R can output R data as latex tables. Used in conjunction with Sweave it is possible to automatically generate tables in a report. Needless to say this provides a really appealing possibility of never typing data into a table again. The only problem is that I think the default latex tables don’t look that great. Enter booktabs…

The booktabs package in latex makes really nice tables, especially if there is math in your table that might run up against the regular `\hline`

in the tabular environment.

Buried away in the xtable documentation are some options that make this possible. See the example below:

\usepackage{booktabs}

\begin{document}

\begin{table}[!h]

\centering

\caption{Check out my table.}

\label{tab:mytable}

<

library(xtable)

mat <- as.data.frame(matrix(rnorm(25),nrow=5))

colnames(mat) <- c("$\\alpha$“,”$\\beta$“,

“$\\gamma$“,”$\\delta$“,

“$\\frac{\\epsilon}{2}$“)

rownames(mat) <- c(‘A’,'B’,'C’,'D’,'E’)

mat <- xtable(mat,digits=rep(5,ncol(mat)+1))

print(mat,

sanitize.text.function = function(x){x},

floating=FALSE,

hline.after=NULL,

add.to.row=list(pos=list(-1,0, nrow(mat)),

command=c(‘\\toprule ‘,

‘\\midrule ‘,

‘\\bottomrule ‘)))

@

\end{table}

\end{document}

To compile, Sweave needs to be run on it. Running Sweave is an pre-processing step in the latex compilation process

$ pdflatex table.tex

and then check out your awesome new table that you didn’t type!

**leave a comment**for the author, please follow the link and comment on their blog:

**cameron.bracken.bz » R**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.