我有一个带有DT数据表的应用。该表按用户输入的某些指定尺寸分组。用户指定1,2,3或4个分组变量时,我希望这些变量的宽度为100px。
要复制的完整代码如下。有问题的特定代码块是:
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)))
)
)
如果我将1:length(input$group_dims)
改为1:3
,那么前三列确实会调整为指定的长度。似乎DT或Shiny无法正确读取输入input $ group_dims的长度。
如何调整前n个列宽,其中列数是取决于用户输入的变量?
要复制的完整代码,请注意,即使我在选择器中选择了所有字段,也只有第一列显示为100px:
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)