Have a look at the xtable
package, which prints LaTeX tables neatly. I have used this a lot for Sweave auto-generated reports.
The following is a toy example of printing some tables for LaTeX in a Sweave document
<<echo=FALSE,print=FALSE,results=tex>>
## generate an example set of tables
library(xtable)
data(tli)
my.tables <- list()
for(iTable in 1:20){
my.tables[[iTable]] <- tli[1:20 + iTable,]
}
## print these out, with page breaks in between
for(iTable in 1:20){
print(xtable(my.tables[[iTable]]))
cat('\\clearpage\n')
}
@
The basic idea of this is that you need to make sure that the tables generated by xtable
don't float; instead you should put them in your own floating environment. In the example below, I've generated two side-by-side tables, each within a {minipage}
environment and each with their own caption using the \captionof
command of the caption
package.
I've formatted the tables using booktabs
. See How can I use a table generated by R in LaTeX? for more details on this.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\usepackage{caption}
\title{Side-by-side xtables}
\author{}
\date{}
\begin{document}
\maketitle
First some R code to create some data.
<<>>=
myData <- matrix(c(19,89,23,23,74,44,16,39,67),ncol=3,byrow=TRUE)
colnames(myData) <- c("A","B","C")
rownames(myData) <- c("1","2","3")
myData2 <- myData * 2
@
Now we place the data in two side-by-side tables:
\begin{table}[htb]
\begin{minipage}{.45\textwidth}
\centering
<<echo=FALSE,results=tex>>=
library("xtable")
print(xtable(myData),
floating=FALSE,
hline.after=NULL,
add.to.row=list(pos=list(-1,0, nrow(myData)),
command=c('\\toprule\n','\\midrule\n','\\bottomrule\n')))
@
\captionof{table}{The first table}
\end{minipage}
\begin{minipage}{.45\textwidth}
\centering
<<echo=FALSE,results=tex>>=
print(xtable(myData2),
floating=FALSE,
hline.after=NULL,
add.to.row=list(pos=list(-1,0, nrow(myData2)),
command=c('\\toprule\n','\\midrule\n','\\bottomrule\n')))
@
\captionof{table}{The second table}
\end{minipage}
\end{table}
\end{document}
Best Answer
As others have pointed out, this is related to
xtable()
using the[ht]
specification for table placement by default. This can be overridden, however. Rather thanin your Sweave file, you can specify
or any other specification. I often use
"H"
from thefloat
package