带有数据表的子表(扩展/折叠)

时间:2019-02-25 07:54:59

标签: r datatables r-markdown

例如,我喜欢用一个子表建立一个数据表:

test = data.table(c(375, 789, 72, 663, 100), c(1237, 1237, 1237, 663, 100), c("abc", "abc", "abc", "d", "e"), c("a","b","c","d","e"))

首先,我喜欢有一张桌子:

datatable(test[, .(V2,V3)][3:5])

在单击abc时,我希望能够扩展该数据表,以便如下所示:

datatable(test[, .(V1, V4)][1:3])

输出将是用rmarkdown编写的html文件。 预先感谢您的帮助和帮助。

1 个答案:

答案 0 :(得分:0)

您可以从这里开始。 基于@Stéphane的答案here

的代码
library(DT)
datatable(
  cbind(' ' = '<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_open.png\"/>', 
        mtcars), escape = -2,
  options = list(
    columnDefs = list(
      list(visible = FALSE, targets = c(0, 2, 3)),
      list(orderable = FALSE, className = 'details-control', targets = 1)
    )
  ),
  callback = JS("
                table.column(1).nodes().to$().css({cursor: 'pointer'});
                var format = function(d) {
                return '<table cellpadding=\"5\" cellspacing=\"0\" border=\"0\" style=\"padding-left:50px;\"> ' +
'<thead>'+
'<tr>'+
            '<th>1st column</th>'+
            '<th>2nd column</th>'+
        '</tr>'+
'</thead>'+
'<tbody>'+
'<tr>'+
            '<td>'+d[2]+'</td>'+
            '<td>'+d[3]+'</td>'+
        '</tr>' +
'</tbody>'
'</table>';
                };
                table.on('click', 'td.details-control', function() {
                var td = $(this), row = table.row(td.closest('tr'));
                if (row.child.isShown()) {
                row.child.hide();
                td.html('<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_open.png\"/>');
                } else {
                row.child(format(row.data())).show();
                td.html('<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_close.png\"/>');
                }
                });"
))

有关更多详细信息,请访问datatable网站here