RMarkdown-使用DT创建列标题

时间:2020-09-03 10:50:54

标签: r r-markdown dt

我想使用RmdDT::datatable中创建一些表。 目前,我的表格如下所示: enter image description here

但是我希望在列上方有一个标头,因此它会在第一个ligne上显示“ Pre”,并在其下显示M和SD。这是一个例子: enter image description here

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

如果您确实想使用DT::datatable,则可以尝试按照答案here中的建议使用解决方案。这涉及到创建HTML表格的“草图”以填充数据单元格。

library(DT)
library(htmltools)

cont <- withTags(
  table(
    class = "display",
    thead(
      tr(
        th(colspan = 2, "Pre"),
        th(colspan = 2, "Post")
      ),
      tr(
        th("M"),
        th("SD"),
        th("M"),
        th("SD")
      ),
    )
  )
)

datatable(df, rownames = FALSE, container = cont, 
          options = list(
            columnDefs = list(
              list(targets = "_all", className = "dt-center")
            )
          ))

数据

df <- structure(list(Pre_M = c(60.23, 59.96, 60.48), Pre_SD = c(8.02, 
7.98, 8.04), Post_M = c(55.15, 56.48, 53.91), Post_SD = c(9.94, 
10.16, 9.55)), class = "data.frame", row.names = c(NA, -3L))

enter image description here

答案 1 :(得分:1)

如果DT::datatable的交互性对您并不重要(如表的简短性所示),我建议使用KableExtra::kable,它可以轻松处理HTML和Latex中的此类标头:{ {3}}。