R: table to HTML with dimension names
The contingency tables printed by R nicely include the dimension names above the factor levels in the first row and first column. Here I have to replace spaces with dots to show how it is printed in the console.
shape=factor(c("round","round","round","spiky"))
color=factor(c("blue","red","blue","red"))
table(shape,color)
.......color
shape...blue.red
..round....2...1
..spiky....0...1
But if you try to print this with the xtable library, you lose the dimension names. This was mentioned also in this thread.
library(xtable)
print(xtable(table(shape,color)),"html")
| blue | red | |
|---|---|---|
| round | 2 | 1 |
| spiky | 0 | 1 |
I wrote a hack to force these dimension names into the resulting table. It’s ugly but it appears to work.
crazytable <- function(x,y,prop=0) {
if (prop == 0) {
xt <- as.data.frame(xtable(table(x,y)))
} else {
xt <- as.data.frame(xtable(prop.table(table(x,y),prop)))
}
cn <- colnames(xt)
rn <- rownames(xt)
t.out <- as.matrix(cbind(c("","",rn),rbind(rep("",ncol(xt)),cn,xt)))
colnames(t.out) <- 1:ncol(t.out)
rownames(t.out) <- 1:nrow(t.out)
t.out[2,1] <- deparse(substitute(x))
t.out[1,2] <- deparse(substitute(y))
t.out
}
print(xtable(crazytable(shape,color)),"html",include.r=FALSE,include.c=FALSE)
| color | ||
| shape | blue | red |
| round | 2 | 1 |
| spiky | 0 | 1 |
Here prop allows for proportion tables along rows (1) or columns (2).
leave a comment