1

I'm trying to create a table using the gridExtra package in R, and I want to have sub column names under a general column name. For example have one large column titled "Urbana-Champaign" that spans over two smaller column names "element" and "number of genes." I have looked everywhere on the gridExtra support site but can't seem to find a way to create overall column names that encompass subcolumns. Does anyone know how?

M--
  • 25,431
  • 8
  • 61
  • 93
  • I would hazard a guess that you cannot, without some really serious hacking at the **grid** code level. – joran Jul 23 '13 at 22:29
  • I've [attempted](https://gist.github.com/baptiste/5561717) a proof-of-concept rewrite of grid.table based on gtable, but never finished it. It tentatively supported multi-line headers, though I could never find a good syntax for them. – baptiste Jul 23 '13 at 23:13
  • I would try to simulate that by arranging 2 tables, one table with just a header and another table with data. – agstudy Jul 23 '13 at 23:16
  • @agstudy the problem is in the details; `grid.table` adjusts the column widths to fit the content, so it's quite hard to align anything from outside with the existing columns. There's only information about the table size, via `grobWidth` and `grobHeight`. – baptiste Jul 23 '13 at 23:18

1 Answers1

0

It's rather easy to get a basic gtable, and add new text to it, but you'd have to add all the formatting and styling of the cells. That's where I always give up -- way too many parameters and options to take care of.

library(gtable)
gtable_add_grobs <- gtable_add_grob #misleading name

d <- head(iris, 3)

extended_matrix <- cbind(c("", rownames(d)), rbind(colnames(d), as.matrix(d))) 

all_grobs <- matrix(lapply(extended_matrix, textGrob), ncol=ncol(d) + 1)

row_heights <- function(m){
  do.call(unit.c, apply(m, 1, function(l)
    max(do.call(unit.c, lapply(l, grobHeight)))))
}

col_widths <- function(m){
  do.call(unit.c, apply(m, 2, function(l)
    max(do.call(unit.c, lapply(l, grobWidth)))))
}

g <- gtable_matrix("table", grobs=all_grobs,
                   widths=col_widths(all_grobs) + unit(4,"mm"), 
                   heights=row_heights(all_grobs) + unit(4,"mm"))

g <- gtable_add_rows(g, unit(1, "line"), 0)
g <- gtable_add_grobs(g, list(textGrob("Sepal's main title"), 
                              textGrob("Petal's main title"))
                     t=1,b=1,l=c(2, 4), r=c(3, 5))

grid.newpage()
grid.draw(g)

enter image description here

baptiste
  • 75,767
  • 19
  • 198
  • 294