Reputation: 985
I have a download handler (say 10 times) that needs to be put in shiny as shown below. So instead of writing it 10 times, I have written a function so that after passing 3 parameters, the render functions should get executed
Button 1
output$downloadData_sec1 <- downloadHandler(
filename = function() {
paste(str_replace("title",pattern = " ", "_"), Sys.Date(), ".csv", sep="_")
},
content = function(file) {
write.csv(display_data$asd, file)
}
)
Button 2
output$downloadData_sec2 <- downloadHandler(
filename = function() {
paste(str_replace("title2",pattern = " ", "_"), Sys.Date(), ".csv", sep="_")
},
content = function(file) {
write.csv(display_data$asd2, file)
}
)
function
download_function <- function (id, title, data){
output[["id"]] <- downloadHandler(
filename = function() {
paste(str_replace(title,pattern = " ", "_"), Sys.Date(), ".csv", sep="_")
},
content = function(file) {
write.csv(display_data[["data"]], file)
}
)
}
But looks like there is some error here . I get output
not defined
Can anyone help me here?
Upvotes: 0
Views: 43
Reputation: 12451
Here's a MWE showing how to implement the your function as a Shiny module. In the interests of brevity, I've limited myself to three instances of the module rather than ten. I've also generated random data within each instance of the module. You can make the obvious changes for your real use case.
library(shiny)
# Download UI
demoUI <- function(id) {
ns <- NS(id)
wellPanel(
id,
tableOutput(ns("data")),
downloadButton(ns("downloadData"), "Download")
)
}
# Download server
demoServer <- function(id, title) {
moduleServer(
id,
function(input, output, session) {
# Generate some random data
d <- data.frame(X=runif(5), y=rnorm(5))
output$data <- renderTable({ d })
output$downloadData <- downloadHandler(
filename = function() {
paste(stringr::str_replace(title, pattern = " ", "_"), Sys.Date(), ".csv", sep="_")
},
content = function(file) {
write.csv(d, file)
}
)
}
)
}
# Main UI
ui <- function() {
fluidPage(
demoUI("demo1"),
demoUI("demo2"),
demoUI("demo3")
)
}
# Main server
server <- function(input, output, session) {
demoServer("demo1", "Random title")
demoServer("demo2", "Another title")
demoServer("demo3", "Something else")
}
shinyApp(ui, server)
Here's a screenshot of (part of) the app:
And of part of my Downloads folder after clicking each Download button and accepting the default filename:
And, finally, the contents of one of the CSV files:
Upvotes: 1