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.



But if you try to print this with the xtable library, you lose the dimension names. This was mentioned also in this thread.


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))


shape blue red
round 2 1
spiky 0 1

Here prop allows for proportion tables along rows (1) or columns (2).


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s