【问题标题】:Table output - grouping column headings for PDF table表格输出 - 为 PDF 表格分组列标题
【发布时间】:2017-03-31 14:39:30
【问题描述】:

我想知道在输出汇总表时是否有任何方法可以有效地对列标题进行分组。我意识到这对我想要的东西的解释很糟糕,所以这里有一个例子。

假设我有一个包含 5 列的摘要数据框:projectName、currMonthCost、currMonthRev、prevMonthCost、prevMonthRev。我希望列标题有 2 个级别,最终输出按 curr/prev 对列进行分组 - 类似于:

               ||     Current    ||    Previous    ||  
  projectName  ||  Cost  |  Rev  ||  Cost  |  Rev  ||
_______________||________|_______||________|_______||
               ||        |       ||        |       ||
       x       ||    x   |   x   ||    x   |   x   ||  
       y       ||    y   |   y   ||    y   |   y   ||

抱歉,我是新来的。但希望你能明白。

有没有可以处理的包?我已经在使用 formattable 但在那里找不到任何明显的东西。如果没有任何现成的东西,我很高兴它是一个完整的垃圾 - 它只是导出为 PDF 的摘要数字。我只是想避免在 PDF 之前必须导出到 excel 来合并单元格。

提前致谢。 詹姆斯

【问题讨论】:

  • 请参阅knitr 包或xtable 包中的kable 函数,以了解表输出的两种可能性。此外,rmarkdown 包可能值得研究以嵌入这些包的输出。

标签: r dataframe formatting columnheader


【解决方案1】:

您需要DT 库。它是显示数据框的一个非常强大的工具。在您的情况下,您可以使用 container 参数自定义表头:

library(DT)

df <- data.frame(projectName = c("x", "y"), currMonthCost = c("x", "y"), currMonthRev = c("x", "y"), prevMonthCost = c("x", "y"), prevMonthRev = c("x", "y"))

df
#  projectName currMonthCost currMonthRev prevMonthCost prevMonthRev
#1           x             x            x             x            x
#2           y             y            y             y            y

sketch = htmltools::withTags(table(
      class = 'display',
      thead(
          tr(
              th(rowspan = 2, 'projectName'),
              th(colspan = 2, 'Current'),
              th(colspan = 2, 'Previous')
          ),
          tr(
              lapply(rep(c('Cost', 'Rev'), 2), th)
          )
      )
  ))

datatable(df, container = sketch, rownames = F)

【讨论】:

    猜你喜欢
    • 2012-03-05
    • 2017-01-05
    • 2017-10-15
    • 2017-04-03
    • 2016-12-26
    • 2021-12-17
    • 2022-11-10
    • 1970-01-01
    • 2010-12-05
    相关资源
    最近更新 更多