gpt4 book ai didi

r - 如何包装 gridExtra::tableGrob() 中特定列的每一行

转载 作者:行者123 更新时间:2023-12-04 10:45:56 27 4
gpt4 key购买 nike

我有以下数据框


df <- structure(list(section_name = c("WWW", "WWW:XXX:YYY", 
"WWW:ZZZ", "WWW:ZZZ:YYY", "WWW:YYY",
"XXX", "XXX:ZZZ:YYY", "XXX:YYY",
"ZZZ", "YYY"), member = c("BATF, TEAD1, RUNX2, POL003.1_GC-box, NFIC, EBF, Rfx5, PB0194.1_Zbtb12_2, E2F7",
"Atf1", "PB0182.1_Srf_2, PB0156.1_Plagl1_2", "MF0010.1_Homeobox_class, MEF2A, CRX",
"BORIS, ETS1, CEBPE", "TEAD4, NFATC3, Mef2b, Sp1, PB0099.1_Zfp691_1, NFY, PH0170.1_Tgif2, PB0117.1_Eomes_2, NFY, LEF1, PB0024.1_Gcm1_1",
"RUNX, CTCF", "JunB", "AP-1, TEAD, KLF5, Fli1, Atf2, NFIA, GFY, POL001.1_MTE, PB0135.1_Hoxa3_2, Ahr::Arnt, NFYA, Arnt:Ahr",
"TEAD3, NFIX, KLF3, Rbpj1, SPDEF, Mef2c, Foxf1, PB0203.1_Zfp691_2, SOX9, HOXC13"
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-10L), .Names = c("section_name", "member"))

df
#> section_name
#> 1 WWW
#> 2 WWW:XXX:YYY
#> 3 WWW:ZZZ
#> 4 WWW:ZZZ:YYY
#> 5 WWW:YYY
#> 6 XXX
#> 7 XXX:ZZZ:YYY
#> 8 XXX:YYY
#> 9 ZZZ
#> 10 YYY
#> member
#> 1 BATF, TEAD1, RUNX2, POL003.1_GC-box, NFIC, EBF, Rfx5, PB0194.1_Zbtb12_2, E2F7
#> 2 Atf1
#> 3 PB0182.1_Srf_2, PB0156.1_Plagl1_2
#> 4 MF0010.1_Homeobox_class, MEF2A, CRX
#> 5 BORIS, ETS1, CEBPE
#> 6 TEAD4, NFATC3, Mef2b, Sp1, PB0099.1_Zfp691_1, NFY, PH0170.1_Tgif2, PB0117.1_Eomes_2, NFY, LEF1, PB0024.1_Gcm1_1
#> 7 RUNX, CTCF
#> 8 JunB
#> 9 AP-1, TEAD, KLF5, Fli1, Atf2, NFIA, GFY, POL001.1_MTE, PB0135.1_Hoxa3_2, Ahr::Arnt, NFYA, Arnt:Ahr
#> 10 TEAD3, NFIX, KLF3, Rbpj1, SPDEF, Mef2c, Foxf1, PB0203.1_Zfp691_2, SOX9, HOXC13

我想在其中创建表格作为图像。我用这段代码来做:

library(gridExtra)
p <- gridExtra::tableGrob(df)
grid.arrange(p)

产生这个的

enter image description here

我的问题是如何将每一行 member 列包装到特定的列宽?

最佳答案

如果您在文本中添加换行符,列宽将基于最长的完整字符串的长度。自动设置换行符的一种方法是使用 stringr 包中的 str_wrap。例如:

library(gridExtra)
library(stringr)

df$member = str_wrap(df$member, 40)

p <- gridExtra::tableGrob(df)
grid.arrange(p)

enter image description here

为了完整起见,我应该提一下,可以直接设置表格列的宽度,但文本不会自动换行,因此会被截断。但是,结合文本换行,这可以让您对列宽进行额外的控制。这是一个显示未包装字符串截断的示例:

library(grid)

# Starting with the original (unwrapped) version of df
p <- tableGrob(df, rows=NULL)
p$widths = unit(c(0.2, 0.5), "npc")

grid.arrange(p)

enter image description here

有关格式化表 grob 的更多信息,请参阅 the Vignette .

关于r - 如何包装 gridExtra::tableGrob() 中特定列的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46701960/

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