在DT

2017-03-07 29 views
4

我想在一个DataTable在DT

页脚添加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 
      ");", 
      "}") 
    ) 
) 

我试图做到这一点对
做到了1列 - 所有列
- 所有NUM列(或所有除焦炭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 
) 
+0

也许会更好地上下移动上述解决其自己的答案,这样就比较容易发现。 – demongolem

回答

4

没有必要一个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 
) 

enter image description here

+0

它的工作谢谢你 –

1

编辑: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)

注意,第一列是一个字符串,所以降低符连接字符串。另外请注意,您可以为开始和结束之间的任何数字这样做。

+0

页脚正在工作,但现在只有页脚为空表 –

+0

已修复。我无意中结束了循环而不是ncol(dt_test)。 –