在 gridExtra R 的 tableGrob 中包装列 headers

Wrap column headers in tableGrob in gridExtra R

我正在创建一个 R 输出,其中包括 2 个 ggplot 图表和一个 tableGrob.

我可以插入 table,但是列名称相当长,因此整个 table 不适合结果文档。

我只想将第 headers 列的文本换行,或者指定每列的大小

一些代码:

library(gridExtra)
ref=c("1234567890", "0987654321")
method=c("type 1", "type 2")
methodref=c("ABC", "DEF")
firstdos=c(as.POSIXct("2015-01-01 00:00:00"), as.POSIXct("2015-02-01 00:00:00"))
lastdos=c(as.POSIXct("2015-01-31 23:45:00"), as.POSIXct("2015-02-28 23:45:00"))
dur=c("31d 0H 0M 0S", "28d 0H 0M 0S")
maxheart=c("90.25", "96")
minheart=c("40.1", "55.3")
meanheart=c("70.5", "69.4")
maxpre=c("85.6", "89.2")
minpre=c("51", "53.2")
meanpre=c("63.8", "71.1")

DF=data.frame(ref,method,methodref,firstdos,dur,lastdos,maxheart,minheart,meanheart,maxpre,minpre,meanpre)

colnames(DF)=c("Reference","Method Name","Method Reference","First Dosage taken","Duration of Medication","Final Dosage taken",
  "Maximum Heartrate (bpm)","Minimum Heartrate (bpm)","Mean Heartrate (bpm)","Maximum heartrate before trial (bpm)",
  "Minimum heartrate before trial (bpm)","Mean heartrate before trial (bpm)")

g5 <- tableGrob(head(DF))
grid.arrange(g5, nrow=1)

此外(我知道这可能值得作为一个单独的问题提出),我目前正在使用 nrow=3(2 个图和 1 个 table)格式化我的 grid.arrange 命令。我希望 table 位于整个地块的顶部,第二行是并排的两个地块。有什么想法吗?

试试这个

cols <- c("Reference","Method Name","Method Reference","First Dosage taken","Duration of Medication","Final Dosage taken",
               "Maximum Heartrate (bpm)","Minimum Heartrate (bpm)","Mean Heartrate (bpm)","Maximum heartrate before trial (bpm)",
               "Minimum heartrate before trial (bpm)","Mean heartrate before trial (bpm)")

colnames(DF) <- sapply(cols, function(x) paste(strwrap(x, width = 10),  collapse="\n"))

g5 <- tableGrob(head(DF))
grid.arrange(g5, ggplot(), ggplot(), 
             layout_matrix=matrix(c(1,1,2,3), ncol=2, byrow=TRUE))