When you apply xtable
on objects of type table
the xtable.table
method is called. This method is defined as follows (code obtained with getAnywhere(xtable.table)
):
function (x, caption = NULL, label = NULL, align = NULL, digits = NULL,
display = NULL, auto = FALSE, ...)
{
if (length(dim(x)) == 1) {
return(xtable.matrix(matrix(x, dimnames = list(rownames(x),
names(dimnames(x)))), caption = caption, label = label,
align = align, digits = digits, display = display,
auto = auto, ...))
}
else if (length(dim(x)) == 2) {
return(xtable.matrix(matrix(x, ncol = dim(x)[2], nrow = dim(x)[1],
dimnames = list(rownames(x), colnames(x))), caption = caption,
label = label, align = align, digits = digits, display = display,
auto = auto, ...))
}
else {
stop("xtable.table is not implemented for tables of > 2 dimensions")
}
}
So, the table is converted to a matrix and then xtable
is called on the matrix. When you convert a list to a matrix the values appear in columns:
> matrix(p2,dimnames=list(rownames(p2)))
[,1]
L 36.39
M 26.39
H 21.67
To change the output you can transpose the table using t()
. For this it is not necessary to use as.table
, you can transpose the result of tapply
directly.
The transpose function creates a rowname [1,]
in the output. To remove this you can use include.rownames=FALSE
. This option is an argument of print.xtable
, not of xtable
itself. Therefore you need to use the print
function explicitly in the code.
R code:
p2 <- round(tapply(breaks, list(tension), mean), digits=2)
p2trans <- t(p2)
p2tab <- xtable(p2trans)
print(p2tab,include.rownames=FALSE)
Full MWE:
\documentclass{article}
\begin{document}
<<echo=FALSE,results='asis'>>=
library(xtable)
attach(warpbreaks)
p2 <- round(tapply(breaks, list(tension), mean), digits=2)
p2trans <- t(p2)
p2tab <- xtable(p2trans)
print(p2tab,include.rownames=FALSE)
@
\end{document}
Result:
