Align text when using tableGrob or grid.table in R

Is this what you are looking for? There is a core.just parameter of the format() call.

require("gridExtra")

n=5
df<- data.frame(x=rnorm(n),y=rnorm(n),z=sample(letters[1:2],n,replace=T))


g1<-tableGrob(
format(df, digits = 1,
     scientific=F,big.mark = ","),
     core.just="left",
     #core.just="right",
     #col.just="right",
     gpar.coretext=gpar(fontsize=8), 
     gpar.coltext=gpar(fontsize=9, fontface='bold'), 
     show.rownames = F,
     h.even.alpha = 0,
     gpar.rowtext = gpar(col="black", cex=0.7,
                            equal.width = TRUE,
                            show.vlines = TRUE, 
                            show.hlines = TRUE,
                            separator="grey")                     
)

grid.draw(g1)

With gridExtra v>=2.0.0, the parameters are now controlled via nested lists (themes),

library(gridExtra)
library(grid)
n=5
d <- data.frame(x=rnorm(n),y=rnorm(n),z=sample(letters[1:2],n,replace=T))

m <- format(d, digits = 1, scientific=F,big.mark = ",")

mytheme <- ttheme_default(core = list(fg_params = list(hjust=0, x=0.1, 
                                                       fontsize=8)),
                          colhead = list(fg_params = list(fontsize=9, 
                                                          fontface="bold"))
                          )
g1 <- tableGrob(m, theme = mytheme, rows=NULL)
grid.newpage()
grid.draw(g1)

Tags:

R