【问题标题】:add a footer in DT在 DT 中添加页脚
【发布时间】:2017-07-27 20:35:31
【问题描述】:

我正在尝试在数据表的页脚中添加一个 colsum

我用https://github.com/rstudio/DT/issues/39 做了一列

sketch <- htmltools::withTags(table(
  tableHeader(cars),
  tableFooter(cars)
))


datatable(cars,container = sketch, rownames = F, 
      options = list(
        footerCallback = JS(
          "function( tfoot, data, start, end, display ) {",
          "var api = this.api();",
          "$( api.column(1).footer() ).html(",
          "api.column(1 ).data().reduce( function ( a, b ) {",
          "return a + b;",
          "} )",  # remove ; here
          ");",
          "}")
      )
)

我正在努力做到这一点
- 所有列
- 所有 num 列(或除 char id 之外的所有列更容易)

编辑:解决方案:)

dt_test <- structure(list(`pathologie principale` = c("Effet toxique des métaux", 
                                                  "Autres résultats anormaux des examens chimiques du sang", "Néphrite tubulo-interstitielle chronique", 
                                                  "Atteintes tubulo-interstitielles et tubulaires dues à des médicaments et des métaux lourds", 
                                                  "Autres maladies     pulmonaires obstructives chroniques", "Autres résultats anormaux de l'examen des urines"
),     Fort = c(12L, 4L, 3L, 2L, 2L, 2L), Moyen = c(2L, 0L, 0L, 0L, 1L, 1L), Faible = c(4L, 0L, 0L, 0L, 4L, 0L)),   
.Names = c("pathologie principale",                  "Fort", "Moyen", "Faible"), class = c("data.table", "data.frame"
), row.names = c(NA, -6L))


sketch <- htmltools::withTags(table(
  tableHeader(dt_test),
  tableFooter(sapply(dt_test, function(x) ifelse( (is.numeric(x)) ,sum(x)     ,"total" ))
)))


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

【问题讨论】:

  • 也许最好将上述解决方案移至自己的答案,以便更容易找到。

标签: css r dt


【解决方案1】:

不需要footerCallback

sketch <- htmltools::withTags(table(
    tableHeader(dt_test),
    tableFooter(sapply(dt_test, function(x) if(is.numeric(x)) sum(x)))
))


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

【讨论】:

    【解决方案2】:

    编辑:GGamba 的答案更简单,应该使用,我仍然想保留正确的 JS 代码以与 footerCallback 一起使用,以便单独处理每一列以供将来参考。

    将调用插入从 0(或您想要的任何列)到结束的 for 循环:

    opts <- list(
    footerCallback = JS(
    "function( tfoot, data, start, end, display ) {",
    "var api = this.api();",
    sprintf("for(var i=1; i<%d; i++) {",ncol(dt_test)),
    "  $( api.column(i).footer() ).html(",
    "  api.column(i ).data().reduce( function ( a, b ) {",
    "    if(isNaN(a)) return ''; return a+b;",
    "  } )",  # remove ; here
    "  );",
    "}}"))
    

    datatable(dt_test, container = sketch, options = opts)

    请注意,第一列是一个字符串,因此 reduce 将字符串连接起来。另请注意,您可以对 start 和 end 之间的任何数字执行此操作。

    【讨论】:

    • 页脚正在工作,但它现在是一个只有页脚的空表
    • 已修复。我不小心将 end 传递给循环而不是 ncol(dt_test)。
    猜你喜欢
    • 2018-10-07
    • 2012-10-19
    • 2015-10-08
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多