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?
Asked
Active
Viewed 2,110 times
1
-
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 Answers
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)

baptiste
- 75,767
- 19
- 198
- 294
-
`gridExtra::tableGrob` is now based on gtable, making this sort of customisation easier. – baptiste Jul 15 '15 at 22:10