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))
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:
We load the Select
extension through extensions = "Select"
. See here for details on potential compatibility issues.
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.