manish p
manish p

Reputation: 187

Collapse DT table columns by default

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?

datatable(
        iris2, rownames = FALSE,
        extensions = 'Buttons', options = list(
          dom = 'Bfrtip',
          buttons = list(list(extend = 'colvis', columns = c(2, 3, 4)))
        )
      )

Upvotes: 3

Views: 535

Answers (1)

Stéphane Laurent
Stéphane Laurent

Reputation: 84599

You have to hide the columns with columnDefs:

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:

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)
    )
  )
)

Upvotes: 2

Related Questions