I am attempting to use a custom download button with a DT datatable. I tried using the add on buttons feature but these do not allow for download of the entire dataframe.
I copied the methodology by stla on this Github issues page (right at the bottom) Downloading all the data using Buttons extension · Issue #267 · rstudio/DT · GitHub.
Reprex:
library(tidyverse)
library(shiny)
library(nycflights13)
library(lubridate)
library(DT)
# 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)
),
# DT table
mainPanel(
downloadButton("download1","Download DF"),
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()},
callback = JS("$('div.dwnld').append($('#download1'));"),
filter = 'top',
extensions = 'Buttons',
options = list(dom = 'B<"dwnld">frtip',
autoWidth = T,
scrollX=T,
buttons = list("copy"),
columnDefs = list(list(width = '100px',targets = 1:length(input$group_dims)))
)
)
output$download1 <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(my_flights_react(), file)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
If you run that Shiny app, when it initially loads a download button appears as expected. However, if you make a election with the input selector, the download button disappears.
How can I adjust this app so that the download option remains after a selection is made by the user?