【问题标题】:Merging Table Header Cells Using tableGrob使用 tableGrob 合并表格标题单元格
【发布时间】:2019-10-31 22:34:07
【问题描述】:

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

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):

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):

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

有没有人能提供合并单元格的方法?

【问题讨论】:

  • dput( SummaryTable )。 PNG 没用。

标签: r merge gridextra


【解决方案1】:

一种方法是使用combine (described here) 向您的表格添加额外的标题行。

使用来自here 的想法,您可以为附加标题行创建tableGrob

然后您可以更改gtablelr 以更正定位。

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)

【讨论】:

  • 谢谢@user20650 我正在使用以下代码为我的表尝试此操作:tab &lt;- tableGrob(SummaryTable[1:9, 2:7], rows=NULL) header &lt;- tableGrob(SummaryTable[1, 1:3], rows=NULL, cols=c("head1", "head2", "head3")) jn &lt;- join(header[1,], tab, along=2) jn$widths &lt;- rep(max(jn$widths), length(jn$widths)) jn$layout[1:7 , c("l","r")] &lt;- list(c(1, 3),c(2, 5),c(4, 7)) 这是我的结果,标题未合并。 i.imgur.com/89UNHt2.png
  • 快到了...试试jn$layout[1:6 , c("l","r")] &lt;- list(c(1, 3, 5),c(2, 4, 6))。值得在更改前后查看jn$layout[1:6 , ] 以查看它们是否有意义)这使用矢量循环,因此left 列是1,3,5,1,3,5right 2,4,6,2,4,6
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多