使用R中的grid.table打印到pdf文件-太多的行无法容纳在一页上 [英] print to pdf file using grid.table in r - too many rows to fit on one page

查看:154
本文介绍了使用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()

这篇关于使用R中的grid.table打印到pdf文件-太多的行无法容纳在一页上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆