DT::datatable 显示

DT::datatable display

在下面的代码中,当 "container=..." 行取消注释时列名消失。

require(DT)

DT::datatable(cars[1:5,]
    #, container=htmltools::tags$table(class="display")
)

在浏览器中查看Page Source,区别如下。容器评论:

"container": "<table>\n  <thead>\n    <tr>\n      <th>speed</th>\n      <th>dist</th>\n    </tr>\n  </thead>\n</table>",

容器未评论:

"container": "<table class=\"display\"></table>",

知道如何让它们都起作用吗?

如果您更改 container 选项,列名似乎会被删除。 如果您查看函数的代码,可用 here,您可以看到第 75 行当您不设置 container:

时会发生什么
  if (missing(container)) container = tags$table(
    id = id,
    tags$thead(tags$tr(lapply(escapeColNames(colnames, escape), tags$th)))
  )

当缺少 container 选项时,将生成一个包含 header 的默认容器。 escapeColNames函数稍后定义,它只是用来清理header个名字。

设置container选项时,此代码不是运行,容器就是您在选项中提供的内容,因此您必须自己添加列名。

例如你可以这样做(没有任何转义):

 DT::datatable(cars[1:5,],
    container=htmltools::tags$table(class="display",
          tags$thead(tags$tr(lapply(as.list(colnames(cars)), tags$th))))
)