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)))
  )
)
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)
    )
  )
)
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)
    )
  )
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With