Reputation: 159
I created a data table in Shiny that uses DT to style values based on the values in a set of hidden columns. The table shows whether Units of a company have hit their goals for Calls and Emails.
The problem is that when I hide the columns (using columnDefs = list(list(targets = c(4, 5), visible = FALSE))
), I can no longer use rownames = FALSE
under the datatable()
call: the table displays with no data. Does anyone know how I can get both these options to work together?
I've used the following articles:
https://rstudio.github.io/DT/010-style.html
How do I suppress row names when using DT::renderDataTable in R shiny?
library(shiny)
library(tidyverse)
library(DT)
x <- tibble(
Unit = c("Sales", "Marketing", "HR"),
Calls = c(100, 150, 120),
Emails = c(200, 220, 230),
Calls_goal = c(1, 0, 0),
Emails_goal = c(0, 1, 1)
)
ui <- fluidPage(
mainPanel(
DT::dataTableOutput("table")
)
)
server <- function(input, output) {
output$table <- DT::renderDataTable({
# Can't use both visible = FALSE and rownames = FALSE
datatable(x,
options = list(
columnDefs = list(list(targets = c(4, 5), visible = FALSE)) # THIS
),
rownames = TRUE) %>% # OR THIS
formatStyle(
columns = c('Calls', 'Emails'),
valueColumns = c('Calls_goal', 'Emails_goal'),
color = styleEqual(c(1, 0), c("red", "black"))
)
})
}
shinyApp(ui = ui, server = server)
Upvotes: 3
Views: 3025
Reputation: 4480
As rownames are also a column, when you set them to false, yo need to reindex the columns you want to hide. So, in your particular case, column 5 no longer exist. Now it is number 4, and the 4th is the 3rd, so your code should look like:
server <- function(input, output) {
output$table <- DT::renderDataTable({
# Can't use both visible = FALSE and rownames = FALSE
datatable(x, rownames=F,
options = list(
columnDefs = list(list(targets = c(3, 4), visible = FALSE) # THIS
)
)) %>% # OR THIS
formatStyle(
columns = c('Calls', 'Emails'),
valueColumns = c('Calls_goal', 'Emails_goal'),
color = styleEqual(c(1, 0), c("red", "black"))
)
})
}
Upvotes: 6