Is it possible to add tickboxes in a DT datatable?

2019-07-14 08:22发布

问题:

I would like to ask if it is possible to add a column with tickboxes in a DT datatable. I tried to use rep(TRUE,5) which works for rhandsontable but not for DT.

library(DT)
datatable(
data.frame(Sel. = rep(TRUE,5),
           Label=paste("Test",as.integer(1:5)),
           Marg=rep(5),
           Avail.=as.integer(rep.int(5,5)),
           Sel =as.integer(rep.int(5,1)),
           stringsAsFactors = FALSE))

回答1:

Yes, it's possible.

We can use the datatable extension Select for that (see here for details).

Here is a minimal RMarkdown example:

---
title: "Untitled"
output: html_document
---

```{r}
library(DT)
library(tidyverse)
datatable(
    iris %>% rowid_to_column("Row") %>% mutate(Row = ""),
    rownames = FALSE,
    extensions = "Select",
    options = list(
        columnDefs = list(list(className = "select-checkbox", targets = 0, orderable = FALSE)),
        select = list(style = "os", selector = "td:first-child")))
```

This produces

A few comments:

  1. We load the Select extension through extensions = "Select". See here for details on potential compatibility issues.

  2. We add row numbers as a new column, and then set all row numbers to empty strings ""; this is a bit hack-y, but if we leave row names (=row numbers) as they are they will show up along-side the checkboxes. I found creating a new empty column, and then setting rownames = FALSE ensures that we have only check-boxes in the empty column. orderable = FALSE in columnDefs then ensures that this column is not sortable.



标签: r dt