How to change names inside filter for booleans in datatable in shiny?
I have a datatable in Shiny where I use the filter
option. When I want to filter a boolean column, I can choose true
and false
. I would like to rename these values. So instead of true
and false
, it should show yes
and no
.
The displayed column entries are not TRUE
or FALSE
but checkboxes. This is important, that's why I add it to the code example.
I had the idea to convert the booleans to factors. Then the filter shows yes
and no
. However, in this case all checkboxes are checked, so this doesn't work. I commented out the line that does the converting in the code below. If there is a solution without this converting step it would be nice.
As I didn't find any option to change the values, I guess, this can only be accomplished with JavaScript code. Unfortunately, I am not really familiar with JavaScript. I hopse someone call help me here.
library(shiny)
library(DT)
library(dplyr)
library(forcats)
set.seed(43)
data <- data.frame(A = rnorm(10),
B = letters[1:10],
C = sample(c(TRUE, FALSE), 10, TRUE))
ui <- fluidPage(
DTOutput("table_id")
)
server <- function(input, output, session) {
output$table_id <- renderDT(
data %>%
# mutate(C = as_factor(if_else(C == TRUE, "yes", "no"))) %>%
datatable(filter = "top",
options = list(
columnDefs = list(
list(
targets = c(3),
render = JS(
"function(data, type, row, meta) {",
" if(type === 'display'){",
" return data ? '<input type=\"checkbox\" disabled checked/>' : '<input type=\"checkbox\" disabled/>';",
" }",
" return data;",
"}"
)
))
)
)
)
}
shinyApp(ui, server)
Your factor C
in your data.frame will pass values of either "yes" or "no"; however, your JS function is checking data
to see if it is TRUE
or FALSE
. If you compare data
with "yes", then the "yes" will be considered TRUE
and "no" will be considered FALSE
. Let me know if this produces the desired behavior.
library(shiny)
library(DT)
set.seed(43)
data <- data.frame(A = rnorm(10),
B = letters[1:10],
C = sample(c(TRUE, FALSE), 10, TRUE))
ui <- fluidPage(
DTOutput("table_id")
)
server <- function(input, output, session) {
output$table_id <- renderDT(
data %>%
mutate(C = as_factor(if_else(C == TRUE, "yes", "no"))) %>%
datatable(filter = "top",
options = list(
columnDefs = list(
list(
targets = c(3),
render = JS(
"function(data, type, row, meta) {",
" if(type === 'display'){",
" return data == \"yes\" ? '<input type=\"checkbox\" disabled checked/>' : '<input type=\"checkbox\" disabled/>';",
" }",
" return data;",
"}"
)
))
)
)
)
}
shinyApp(ui, server)