gpt4 book ai didi

r - 如何在R中的tableGrob输出表中合并垂直单元格?

转载 作者:行者123 更新时间:2023-12-04 21:35:21 25 4
gpt4 key购买 nike

我有一个类似于此处的问题,其中 OP 旨在合并表 horizontal merging 中存在的列的标题.在这里,我希望合并垂直排列的单元格组。以下是我在 Microsoft Excel 软件中制作的目标表格设计:-

enter image description here

我尝试使用 horizontal merging 为问题规定的方法制作目标表

library(gridExtra)
library(grid)
library(ggplot2)

alphabets <- c(rep("A", 3), rep("B", 3), rep("C",3))
numbers <- c(rep(c(1,2,3), 3))
sounds <- c('Ayes','Bees','Cees')

df1 <- data.frame(alphabets = alphabets,numbers=numbers)
df2 <- data.frame(sounds = sounds)

tab1 <- tableGrob(df1,theme = ttheme_default(),row=NULL)
tab2 <- tableGrob(df2,theme = ttheme_default(),row=NULL)

halign <- combine(tab2,tab1, along =1)

grid.draw(halign)

这会给我以下输出:-

enter image description here

我现在有一个临时工作。但是如果我合并偶数个单元格,它就会失败。
sounds <- c('','Ayes','','','Bees','','','Cees','')
df2 <- data.frame(sounds = sounds)
tab2 <- tableGrob(df2,theme = ttheme_default(),row=NULL)
halign <- combine(tab2,tab1, along =1)
grid.draw(halign)

这个的输出是:-

enter image description here

我的问题是如何合并两个表 grob 对象并保持最终输出的最大表的长度。

感谢您的努力,这些答案将大大有助于我的分析结果的呈现。

干杯

Lune3141

最佳答案

为什么不先设置位置,然后发送到tableGrob ?

# Set locations you want to put sounds at
df2$toBind <- c(2, 5, 8)

# Set locations to allow merge
df1$toBind <- 1:nrow(df1)

# Merge them together
toPrint <-
right_join(df2, df1) %>%
mutate(sounds = ifelse(is.na(sounds)
, ""
, as.character(sounds))) %>%
select(-toBind)

grid.table(toPrint, row = NULL)

生成您上面的表格,但它需要您手动设置您想要的位置。

更大的问题可能是您在这里尝试完成什么,以及为什么您不想重复 sounds柱子。根据您的输出目标,您可能需要查看 LaTeX 中的 booktabs 之类的东西。

很抱歉造成困惑 - 我正在寻找一种更可靠的方法来生成您在问题结束时拥有的表格。这似乎是生成“合并”单元格外观所需的操作:
halign$layout[halign$layout$t != 1 &
halign$layout$l == 1, c("t")] <-
c(2,5,8,2,5,8)

halign$layout[halign$layout$b != 1 &
halign$layout$l == 1, c("b")] <-
c(4,7,10,4,7,10)

grid.draw(halign)

这是在不是第一行(分别为 l == 1t != 1)的第一列( b != 1 )中查找所有内容,并将顶部和底部设置为新位置。您要么需要手动调整位置,要么为您的实际数据以编程方式进行调整(例如,它应该匹配多少行,并对其进行算术运算)。

enter image description here

另外,为了使合并的行更加突出,您可能需要考虑在生成 tab2 时设置不同的背景颜色。格罗布。例如。,:
tab2 <- tableGrob(df2
, theme = ttheme_default(core=list(bg_params = list(fill = c("white","darkgrey"), col=NA)) )
, rows = NULL)

enter image description here

偶数行的示例:
halign_alt <- combine(tab2,tab3, along =1)

halign_alt$layout[halign_alt$layout$t != 1 &
halign_alt$layout$l == 1, c("t")] <-
c(2,5,7,2,5,7)

halign_alt$layout[halign_alt$layout$b != 1 &
halign_alt$layout$l == 1, c("b")] <-
c(4,6,9,4,6,9)

grid.draw(halign_alt)

enter image description here

关于r - 如何在R中的tableGrob输出表中合并垂直单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39726423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com