Search code examples
rdatatablesdt

Specify columns to remain hidden at all times and all screen widths in DataTables in R


Question

When making an interactive table using the DataTables library, columns are hidden under a green + sign when the screen width becomes too narrow for the number and width of columns. Is it possible to specify column(s) to remain hidden at all times – even if the screen is wide enough to display them?

I am using the R DT library in flexdashboard, but I expect this question is relevant for other uses of DataTables (e.g. in javascript).

Example code

In the example below, I would like column_5 to remain hidden at all times:

library(DT)

df <- data.frame(column_1 = 1:10, 
             column_2 = rep(1,10), 
             column_3 = rep("some text"),
             column_4 = seq(2,29,3),
             column_5 = 5:14)

datatable(df,
      extensions = "Responsive",
      options = list(columnDefs = list(
        list(responsivePriority = 9999999999, targets = 5)
      )))

I have tried setting its priority to be hidden to a very large number (using the same idea as explained by @andrewJames here), but this doesn’t work if the screen is wide enough to display all 5 columns.

See also these 2 related questions:


Solution

  • You can use the class name "none" to force the column to always be hidden. To be clear, the data is still visible by clicking on the green plus icon.

    DataTables - Reference

    datatable(
      df,
      rownames = FALSE,
      extensions = "Responsive",
      options = list(columnDefs = list(
        list(className = "none", targets = 4)
      ))
    )
    

    If you don't want the column and data associated with the column to be visible you can use the visible arg.

    columnDefs = list(
      list(visible = FALSE, targets = your_cols)
    )