R: xtable caption (or comment)

user702432 picture user702432 · May 28, 2011 · Viewed 9.9k times · Source

I want to put a comment under a table printed out by xtable. I figured that the best option would be to use the "caption" option: xtable(tablename, caption="This is a caption"). But this is somehow putting in a "Table 1" automatically, so that the output looks like:

Table 1: This is a caption.

Is there any way to suppress this or any simpler way of putting in a comment simply as an additional last row in the table?

Answer

Waldir Leoncio picture Waldir Leoncio · Feb 20, 2012

First, some mock data:

x <- sample(LETTERS, 5, replace = TRUE)
y <- sample(LETTERS, 5, replace = TRUE)
z <- table(x, y)

Now here's a somewhat clumsy solution, using print.xtable's add.to.row argument.

comment          <- list()
comment$pos      <- list()
comment$pos[[1]] <- c(nrow(z))
comment$command  <- c(paste("\\hline \n",  # we`ll replace all default hlines with this and the ones below
                            "your footnote, caption or whatever.  \n",
                            sep = ""))
print(xtable(z),
      add.to.row = comment,
      hline.after = c(-1, 0))  # indicates rows that will contain hlines (the last one was defined up there)

If you want your comment to be placed before the data, use comment$pos[[1]] <- c(0) instead of comment$pos[[1]] <- c(nrow(z)) and adjust hline.after accordingly.

Here's my output:

% latex table generated in R 2.14.1 by xtable 1.7-0 package
% Mon Feb 20 02:17:58 2012
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrrrr}
\hline
& B & C & P & V \\ 
\hline
A &   0 &   0 &   0 &   1 \\ 
D &   1 &   0 &   0 &   0 \\ 
I &   0 &   0 &   0 &   1 \\ 
P &   0 &   0 &   1 &   0 \\ 
Z &   0 &   1 &   0 &   0 \\ 
\hline
your footnote, caption or whatever.  
\end{tabular}
\end{center}
\end{table}