使用tableGrob合并表标题单元格 [英] Merging Table Header Cells Using tableGrob

查看:123
本文介绍了使用tableGrob合并表标题单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用以下方式创建表格图像:

I am currently creating a table image using:

SummaryTable <- data.frame(
  index,

  xa,
  xb,

  ya,
  yb,

  za,
  zb

)
names(SummaryTable) <- c("Index",
                         "Main X Sub A",
                         "Main X Sub B",
                         "Main Y Sub A",
                         "Main Y Sub B",
                         "Main Z Sub A",
                         "Main Z Sub B")

tt <- ttheme_default(colhead=list(fg_params = list(parse=TRUE)))
tbl <- tableGrob(SummaryTable, rows=NULL, theme=tt)

grid.arrange(tbl,as.table=TRUE) 

输出:

使用dput(SummaryTable):

Using dput( SummaryTable ):

structure(list(Index = 0:8, `Main X Sub A` = c(1, 0.69, 0.61, 
0.56, 0.5, 0.44, 0.4, 0.36, 0.33), `Main X Sub B` = c(0.86, 0.62, 
0.51, 0.42, 0.36, 0.31, 0.27, 0.24, 0.23), `Main Y Sub A` = c(1, 
0.8, 0.74, 0.68, 0.63, 0.56, 0.52, 0.47, 0.43), `Main Y Sub B` = c(0.86, 
0.77, 0.67, 0.59, 0.53, 0.47, 0.43, 0.39, 0.36), `Main Z Sub A` = c(0, 
0.17, 0.23, 0.27, 0.33, 0.37, 0.42, 0.46, 0.49), `Main Z Sub B` = c(0, 
0.24, 0.33, 0.42, 0.48, 0.55, 0.6, 0.64, 0.66)), .Names = c("Index", 
"Main X Sub A", "Main X Sub B", "Main Y Sub A", "Main Y Sub B", 
"Main Z Sub A", "Main Z Sub B"), row.names = c(NA, -9L), class = "data.frame")

但是,我想合并顶部标题以实现此输出(以png或pdf格式):

However, I would like to merge the top headers to achieve this output (as png or pdf):

此表是在Excel中创建的. X,Y和Z在合并的单元格内.

This table was created in Excel. X, Y and Z are within merged cells.

有人能协助合并细胞的方法吗?

Is anyone able to assist with methods on merging cells?

推荐答案

一种方法是使用combine(

One way would be to use combine (described here), to add an additional header row to your table.

使用此处的想法,您可以为附加标题行.

Using an idea from here you can create a tableGrob for the additional header row.

然后可以更改gtablelr以更正位置.

You can then alter the l, and r of the gtable to correct the positioning.

library(grid)
library(gridExtra)

# example data & header row
tab <- tableGrob(mtcars[1:3, 1:4], rows=NULL)
header <- tableGrob(mtcars[1, 1:2], rows=NULL, cols=c("head1", "head2")) 

jn <- gtable_combine(header[1,], tab, along=2)
jn$widths <- rep(max(jn$widths), length(jn$widths)) # make column widths equal
#grid.newpage()
#grid.draw(jn) # see what it looks like before altering gtable

# change the relevant rows of gtable
jn$layout[1:4 , c("l", "r")] <- list(c(1, 3), c(2, 4))

grid.newpage()
grid.draw(jn)

这篇关于使用tableGrob合并表标题单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆