0
votes

I'm creating a datatable in R which has child rows, manually-defined column names and also hides a few columns.

This seemed fairly trivial based on an example provided in the DT manual https://rstudio.github.io/DT/002-rowdetails.html (i.e. it already shows how to create the child rows and hide some of the columns). However, when I try adding the 'colnames' argument to define the new column names of the non-hidden columns it doesn't behave as expected.

I have tried removing the blank column header text, adding extras to see if it's relating to the original number of columns in the table. If I remove the call to hide certain columns the headers show as they should but I can't delete columns (they need to be hidden) because the table is linked to plot objects that use the data from those hidden columns.

library(DT)

datatable(
  cbind(' ' = '⊕', mtcars), escape = -2,
  colnames = c(" ", "GEAR COLUMN", "CARB COLUMN"), # This is the only line added to the original DT example.
  options = list(
    columnDefs = list(
      list(visible = FALSE, targets = c(0, 2, 3:10)), # Removing this line solves the header issue but then all columns are shown.
      list(orderable = FALSE, className = 'details-control', targets = 1)
    )
  ),
  callback = JS("
  table.column(1).nodes().to$().css({cursor: 'pointer'});
  var format = function(d) {
    return '<div style=\"background-color:#eee; padding: .5em;\"> Model: ' +
            d[0] + ', mpg: ' + d[2] + ', cyl: ' + d[3] + '</div>';
  };
  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('&oplus;');
    } else {
      row.child(format(row.data())).show();
      td.html('&CircleMinus;');
    }
  });"
  ))

No error messages are provided, it just displays as normal but without all the defined column headers.

I suspect this is a relatively simple thing that makes perfect sense to those experienced in the JS call, but unfortunately that's not my forte.

1

1 Answers

1
votes

If you want to rename the gear and the carb columns, you can do

colnames = c("GEAR COLUMN" = "gear", "CARB COLUMN" = "carb")