Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapse DT table columns by default

Tags:

r

dt

As per below the documentation (https://rstudio.github.io/DT/extensions.html), the below code should collapse first and second columns by default(0,1), but when tried it is displaying all columns by default.

Can we have only 2 columns displayed by default?

DT::datatable(
  iris,
  rownames = FALSE,
  extensions = 'Buttons',
  options = list(
    dom = 'Bfrtip',
    buttons = list(list(extend = 'colvis',
                        columns = c(2, 3, 4)))
  )
)
like image 461
manish p Avatar asked Oct 27 '25 14:10

manish p


1 Answers

You have to hide the columns with columnDefs:

DT::datatable(
  iris,
  rownames = FALSE,
  extensions = 'Buttons',
  options = list(
    dom = 'Bfrtip',
    buttons = list(list(extend = 'colvis',
                        columns = c(2, 3, 4))),
    columnDefs = list(
      list(targets = c(2, 3, 4),
           visible = FALSE)
    )
  )
)

EDIT

In your comments, you ask for a "Show all" feature (you should have opened a new question, but well). Here is the way I found:

DT::datatable(
  iris,
  rownames = FALSE,
  extensions = 'Buttons',
  options = list(
    dom = 'Bfrtip',
    buttons = list(
      list(
        extend = 'colvis', 
        columns = c(2, 3, 4)
      ),
      list(
        extend = 'colvisGroup', 
        text = "Show all",
        show = ":hidden"
      ),
      list(
        extend = 'colvisGroup', 
        text = "Show none",
        hide = ":visible"
      )
    ),
    columnDefs = list(
      list(targets = c(2, 3, 4),
           visible = FALSE)
    )
  )
)
like image 179
Stéphane Laurent Avatar answered Oct 30 '25 07:10

Stéphane Laurent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!