Question

I generated a 20Cx10R table with tableGrob and found it very slow. I thus tried to figure out why. Baptiste himself mentioned the reason in Has anyone else noticed that tableGrob is slow?.

I tried his example in: http://rpubs.com/baptiste/ftableGrob. Initial run was good, i.e. the table in his example generated very quickly.

But when I tried to load gridExtra to add a plot from ggplot, grid.draw(g) generated this error: Error in as.matrix(d) : object 'd' not found

My code is here (modified slightly from baptiste's original):

library(grid)
library(gridExtra)  # NOTE: Loading gridExtra clashes w grid.draw(g) later

aa <- head(iris, 10)
padding = unit(4, "mm")

nc <- ncol(aa)
nr <- nrow(aa)

extended_matrix <- cbind(c("", rownames(aa)), rbind(colnames(aa), as.matrix(aa)))
w <- apply(extended_matrix, 2, strwidth, "inch")
h <- apply(extended_matrix, 2, strheight, "inch")

widths <- apply(w, 2, max)
heights <- apply(h, 1, max)

padding <- convertUnit(padding, unitTo = "in", valueOnly = TRUE)

x <- cumsum(widths + padding) - 0.5 * padding
y <- cumsum(heights + padding) - padding

rg <- rectGrob( x = unit(x - widths/2, "in"), y = unit(1, "npc") - 
                 unit(rep(y, each = nc + 1), "in"), 
               width = unit(widths + padding, "in"), 
               height = unit(heights + padding, "in") )
tg <- textGrob( c(t(extended_matrix)), x = unit(x - widths/2, "in"), 
               y = unit(1, "npc") - unit(rep(y, each = nc + 1), "in"), 
               just = "center" )

g <- gTree( children = gList(rg, tg), x = x, y = y, widths = widths, 
           heights = heights, cl = "table", 
            gp=gpar(fill = rep(c("grey90", "grey95"), each = 2)))

l <- linesGrob()
grid.draw(l)  # Added to show that grid.draw works here...

grid.draw(g)  # ... but not here *confused*
invisible(g)

grid.arrange( g, g, ncol=2)  # I eventually hope to use ggplot2 w the tables drawn with grid.draw

## End of code ##

I researched on this but did not find similar reports/posts. I suspect it's due to my poor understanding of gridExtra, so I am bringing this up in SO to seek 'enlightenment'. Would appreciate if someone could help!

An aside: as baptiste's original code also uses 'd', after switching his 'd' to 'aa', R still screamed "object 'd' not found!". Imagine my bewilderment!

Finally, wish all in SO a Happy New Year (2014)!

Was it helpful?

Solution

When you load gridExtra, you bring with it a drawDetails method (called by grid.draw) for objects of class "table" that is not compatible with this gTree (it lacks some attributes). To cut the story short, you should simply remove the cl = "table" in your gTree, or pick another name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top