使用 r 中的 grid.table 打印到 pdf 文件 - 太多行无法显示在一页上
我正在尝试使用 R 的 gridExtra 包中的 grid.table 将大约 40 行和 5 列的数据帧输出到 .pdf 文件.
I'm trying to output a dataframe of about 40 rows and 5 columns to a .pdf file using grid.table in gridExtra package of R.
但是,40 行对于一个页面来说太长了,所以 .pdf 文件只显示了数据框的一部分.我想知道是否可以在一页上打印两列,以便所有行都显示在一页上.或者,我需要知道如何在多页上打印数据框.谢谢,约翰
However, 40 rows is too long for a page so the .pdf file only shows part of the dataframe. I want to know if I can print two columns on one page so all of the rows show up on one page. Alternatively, I need to know how to print the dataframe over multiple pages. Thanks, John
我建议采用以下策略:创建 tableGrob,查询其高度,拆分行以适合每个页面,
I'd suggest the following strategy: create the tableGrob, query its heights, split the rows to fit each page,
library(gridExtra)
library(grid)
d <- iris[sample(nrow(iris), 187, TRUE),]
tg <- tableGrob(d, rows = seq_len(nrow(d)))
fullheight <- convertHeight(sum(tg$heights), "cm", valueOnly = TRUE)
margin <- unit(0.51,"in")
margin_cm <- convertHeight(margin, "cm", valueOnly = TRUE)
a4height <- 29.7 - margin_cm
nrows <- nrow(tg)
npages <- ceiling(fullheight / a4height)
heights <- convertHeight(tg$heights, "cm", valueOnly = TRUE)
rows <- cut(cumsum(heights), include.lowest = FALSE,
breaks = c(0, cumsum(rep(a4height, npages))))
groups <- split(seq_len(nrows), rows)
gl <- lapply(groups, function(id) tg[id,])
pdf("multipage.pdf", paper = "a4", width = 0, height = 0)
for(page in seq_len(npages)){
grid.newpage()
grid.rect(width=unit(21,"cm") - margin,
height=unit(29.7,"cm")- margin)
grid.draw(gl[[page]])
}
## alternative to explicit loop:
## print(marrangeGrob(grobs=gl, ncol=1, nrow=1, top=NULL))
dev.off()