I have an app with a DT datatable. The table groups by some specified dimensions input by the user. Where the user specifies 1,2,3 or 4 grouping variables, I would like these variables to have a width of 100px.
The full code to reproduce is below. The specific code block in question is:
output$eg_table <- DT::renderDT({my_flights_react() },
filter = 'top', options = list(dom = 'tip',
autoWidth = T,
scrollX=T,
columnDefs = list(list(width = '100px',
targets = 1:length(input$group_dims)))
)
)
If I change 1:length(input$group_dims)
to instead be 1:3
then the first 3 columns will indeed adjust to the specified length. It seems DT or Shiny cannot properly read in the length of the input input$group_dims.
How can I adjust the first n number of column widths where the number of columns is a variable dependent upon user input?
Full code to reproduce, note only the first column shows as 100px, even if I select all the fields in the selector:
library(tidyverse)
library(shiny)
library(nycflights13)
library(lubridate)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Example Shiny App"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput(inputId = "group_dims",
label = "group_dims",
choices = c("carrier", "origin", "dest", "tailnum"),
selected = c("carrier"),
multiple = T) # There can be only one
),
# DT table
mainPanel(
DT::dataTableOutput("eg_table")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
# initial preprocessing
my_flights <- flights %>%
filter(month == 11 & day >= 14) %>% # just data for 2 weeks
mutate(date = ymd(paste(year, month, day, sep = "-"))) %>%
select(date, carrier, origin, dest, tailnum, distance) %>%
mutate(date = ordered(format(date, "%d-%b"), levels = format(sort(unique(date)), "%d-%b")))
# recative preprocessing
my_flights_react <- reactive({
dims <- input$group_dims
my_flights %>%
group_by_at(vars(date, dims)) %>%
summarise(distance = sum(distance)) %>%
pivot_wider(names_from = date, values_from = distance) %>%
replace(is.na(.), 0) %>%
ungroup() %>%
add_column(Total = rowSums(select(., -dims), na.rm = T), .after = length(dims)) %>%
arrange(desc(Total))
})
output$eg_table <- DT::renderDT({my_flights_react() },
filter = 'top', options = list(dom = 'tip',
autoWidth = T,
scrollX=T,
columnDefs = list(list(width = '100px',
targets = 1:length(input$group_dims)))
)
)
}
# Run the application
shinyApp(ui = ui, server = server)