Lune3414 Lune3414 - 2 months ago 19
R Question

Combine on tableGrob objects fails when used serially in a loop?

Everyone I am trying to build tableGrob objects dynamically as new data arrives and I generate results as they become availale to me. Here is an attempt I made to generate such tables but for some reason the

combine()
function is not working as expected.

My code is as follows:

library(gridExtra)
library(grid)
library(ggplot2)

alphabets <- c(rep("A", 3), rep("B", 3), rep("C",3))
numbers <- c(rep(c(1,2,3), 3))

df1 <- data.frame(alphabets = alphabets[1:4],numbers=numbers[1:4])
df2 <- data.frame(alphabets = alphabets[1:4],numbers=numbers[1:4])
df3 <- data.frame(alphabets = alphabets,numbers=numbers)

tab1 <- tableGrob(df1,theme = ttheme_default(),row=NULL)
tab2 <- tableGrob(df2,theme = ttheme_default(),row=NULL)
tab3 <- tableGrob(df3,theme = ttheme_default(),row=NULL)

g1 <- combine(tab1,tab2,along = 2)# 1st combine operation
g2 <- combine(g1,tab3,along = 1)#second combine operation

grid.arrange(g2)


The output is missing a table from the g1 tableGrob object.

enter image description here

Any ideas why this could be happening?

Answer

The combine family of functions is largely experimental; I stole it from gtable where it had a few more bugs, but it's still not fully functional. The logic, IIRC, is to align based on row/column names. This is where the combined g1 table is problematic because its row names are not unique. Fix them, and it works fine,

g1$rownames <- paste0("r", seq_len(nrow(g1)))

enter image description here

(needless to say, PR are welcome)