Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I customize particular columns for a tableGrob in R?

I'm looking to customise particular columns in my tableGrob, for this reproducible example I have chosen to look at customising justification.

Say you have the following dataframe:

df <- data.frame(Order = c(1:3), Name = c("Adam", "Ben", "Charlie"), Score = c(4, 8, 9))

And you want to use the package gridExtra to present the table:

dfGrob <- tableGrob(df, rows = NULL)
grid.arrange(dfGrob)

You can adjust the alignment of the columns by adjusting the theme used to build the grob, for example:

tt1 <- ttheme_default(core=list(fg_params=list(hjust= 0, x=0.05)),
                  colhead=list(fg_params=list(hjust=0, x=0.1)))


dfGrob <- tableGrob(df, rows = NULL, theme = tt1)
grid.arrange(dfGrob)

However, this adjusts the justification for all columns. Say I just want to left justify the Order Column, and leave the others in their central justification position, how would I do that?

I have experimented with:

tt1 <- ttheme_default(core=list(fg_params=list(hjust= c(0, 0.5, 0.5), x=c(0.15, 0.5, 0.5))),
                  colhead=list(fg_params=list(hjust=1, x=0.95)))

dfGrob <- tableGrob(df, rows = NULL, theme = tt1)
grid.arrange(dfGrob)

But this just seems to customise by row. How do I adjust this code to customise by column instead?

like image 920
Will T-E Avatar asked Apr 06 '16 14:04

Will T-E


1 Answers

it's a bit fiddly but you can specify the parameters for all elements,

library(grid)
library(gridExtra)

df <- data.frame(Order = c(1:3),
                 Name = c("Adam", "Ben", "Charlie"), 
                 Score = c(4, 8, 9))

hj <- matrix(c(0, 0.5, 1), ncol=3, nrow=nrow(df), byrow=TRUE)
x <- matrix(c(0, 0.5, 1), ncol=3, nrow=nrow(df), byrow=TRUE)

tt1 <- ttheme_default(core=list(fg_params=list(hjust = as.vector(hj), 
                                               x = as.vector(x))),
                      colhead=list(fg_params=list(hjust=1, x=0.95)))


dfGrob <- tableGrob(df, rows = NULL, theme = tt1)
grid.newpage()
grid.draw(dfGrob)

The recycling logic defaults to column wise, because most often a table has rows of alternating colours. It should be possible to special-case the horizontal justification parameters to make this a bit more user-friendly. Feel free to submit a PR.

enter image description here

like image 137
baptiste Avatar answered Oct 26 '22 07:10

baptiste