GridExtra:将文本右对齐

GridExtra: Align text to right

我正在使用 R 的 gridExtra 包。
我想将第二列的数字向左对齐,而不更改第一列名称的对齐方式。可能吗? 谢谢!

library(gridExtra)
library(grid)

names=c("name1","name2","name3","long name","very long name")
values1=c(100000000,70000,20,600000000000000000,500)
values1=format(values1,big.mark=".",decimal.mark=",",scientific=FALSE)

d=data.frame(names=names,values1=values1)
g1 <- tableGrob(d)
grid.newpage()
grid.draw(g1)

谢谢。

你可以试试这个:

library(gridExtra)
names=c("name1","name2","name3","long name","very long name")
values1=c(100000000,70000,20,600000000000000000,500)
values1=format(values1,big.mark=".",decimal.mark=",",scientific=FALSE)
d <- data.frame(names=names,values1=values1)

g1 <- tableGrob(d[,1, drop = FALSE])
tt2 <- ttheme_default(core = list(fg_params=list(hjust=1, x=1)),
                      rowhead = list(fg_params=list(hjust=1, x=1)))
g2 <- tableGrob(d[,2, drop = FALSE], rows = NULL, theme = tt2)

grid.arrange(arrangeGrob(grobs = list(g1, g2 ), nrow = 1) , widths = c(1,1))

使用 Accessing existing grobs in the table section of the gridExtra wiki 中的想法,您可以编辑 gtable直接。

g1 <- tableGrob(d)

# identify the grobs to change 
# third column of gtable and core foreground text
id <- which(grepl("core-fg", g1$layout$name ) & g1$layout$l == 3 )

# loop through grobs and change relevant parts
for (i in id) {
      g1$grobs[[i]]$x <- unit(1, "npc")
      g1$grobs[[i]]$hjust <- 1
      }

grid.newpage()
grid.draw(g1)

还有一个选择,

g1 <-  tableGrob(d[,-2, drop=FALSE])
g2 <- tableGrob(d[,2, drop=FALSE], rows = NULL,
                theme = ttheme_default(core = list(fg_params=list(hjust=1, x=0.95))))
g <- gtable_combine(g1,g2)
grid.newpage()
grid.draw(g)