Archive for May 30th, 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
\documentclass{article}
\usepackage{booktabs}

\begin{document}

\begin{table}[!h] 
\centering
\caption{This is my table.}
\label{tab:table1}
<<mytable,echo=F,results=tex>>=
mat <- as.data.frame(matrix(runif(25),nrow=5))
colnames(mat) <- c("$\\alpha$","$\\beta$",
"$\\gamma$","$\\delta$","$\\frac{\\epsilon}{2}$")
rownames(mat) <- c(‘A’,’B’,’C’,’D’,’E’)
mat <- xtable::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\n',
        '\\midrule\n','\\bottomrule\n')))
@
\end{table}
\end{document}

 

You can use to compile:

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

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

\def\toprule{\noalign{\ifnum0=`}\fi
  \@aboverulesep=\abovetopsep
  \global\@belowrulesep=\belowrulesep 
  \global\@thisruleclass=\@ne
  \@ifnextchar[{\@BTrule}{\@BTrule[\heavyrulewidth]}}
\def\midrule{\noalign{\ifnum0=`}\fi
  \@aboverulesep=\aboverulesep
  \global\@belowrulesep=\belowrulesep
  \global\@thisruleclass=\@ne
  \@ifnextchar[{\@BTrule}{\@BTrule[\lightrulewidth]}}
\def\bottomrule{\noalign{\ifnum0=`}\fi
  \@aboverulesep=\aboverulesep
  \global\@belowrulesep=\belowbottomsep
  \global\@thisruleclass=\@ne
  \@ifnextchar[{\@BTrule}{\@BTrule[\heavyrulewidth]}}
set.seed(34567)
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
b<-coef(fit)[1]
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.

 
regression1

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:

sprinf(“%3.2f”,pi)

[1] “3.14”

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