Archive for May, 2015

Booktabs package and Sweave

The booktabs package in latex makes really beautiful tables. This package provide some additional commands to enhance the quality of table in LaTeX, especially if there is math in your table that might run up against the regular \hline in the tabular environment. I created a table with the following code:

% file: example.Rnw
% require xtable


\caption{This is my table.}
mat <-,nrow=5))
colnames(mat) <- c("$\\alpha$","$\\beta$",
rownames(mat) <- c(‘A’,’B’,’C’,’D’,’E’)
mat <- xtable::xtable(mat,digits=rep(5,ncol(mat)+1))
sanitize.text.function = 
        nrow(mat)), command=c('\\toprule\n',


You can use to compile:

$ R CMD Sweave example.Rnw
$ pdflatex example.tex

The definition of \toprule\midrule and \bottomrule from
booktabs package is:

x <- runif(10); y <- 4*x+rnorm(10) 
fit <- lm(y~x)
r2 <- summary(fit)$r.squared

# plot data and regression line
plot(x, y)
abline(fit, col=2)

# add text to plot with legend()
legend('topleft', title='option 1', 
legend=sprintf("y = %3.2fx %+3.2f, R\UB2 = %3.2f", 
coef(fit)[2],coef(fit)[1], r2), bty='n', cex=0.7) 

# if you prefer a space between plus/minus and b
if(b<0) {b_sign='-'; b=-b} else {b_sign= '+'}
legend('topright', title='option 2', 
legend=sprintf("y = %3.2f x %s %3.2f, R\UB2 = %3.2f", 
coef(fit)[2],b_sign,b,r2), bty='n',cex=0.7)

Important: R\UB2B2 defined R square symbol. B2 is the hex code for UTF-8 character ² and \U is a control sequence that will call that character.


Decimal places in R plot legend?

For specifying the number of digits, tipically we use the command round, for example:

round(pi, digits=2)

[1] 3.14

However, we can also use sprintf  command to deal with both the number of digits and the + or – in your equation, for example:


[1] “3.14”

Note that, 3.2f controls the number of digits and the symbol forces the + or sign in a equation.