我有以下数据框
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)
哪个产生了这个
我的问题是如何将每行member
列包装到某个列宽?
答案 0 :(得分:3)
如果在文本中添加换行符,则列宽将基于最长的不间断字符串的长度。自动设置换行符的一个选项是使用str_wrap
包中的stringr
。例如:
library(gridExtra)
library(stringr)
df$member = str_wrap(df$member, 40)
p <- gridExtra::tableGrob(df)
grid.arrange(p)
为了完整起见,我应该提一下,可以直接设置表格列的宽度,但文本不会自动换行,因此会被截断。但是,与文本换行相结合,可以进一步控制列宽。这是一个显示截断未打包字符串的示例:
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)
有关格式化表格的更多信息,请参阅the Vignette。
答案 1 :(得分:2)