I have a code block like so:
output$downloadTransactions <- downloadHandler(
filename = function() {
paste('transactions', Sys.Date(), '.csv', sep='')
},
content = function(file) {
write.csv(transactions_table, file)
}
)
This creates a download button on one of my tables shown by my shiny app and it works as is. In this case it's for downloading transaction data, but I have other metrics I would like the user to be able to download, including sessions and revenue.
Since I make several calls to downloadHandler()
, each with minimal variation (metric name and the data frame to be downloaded), I wanted to attempt to write it as a function.
Tried:
# for download button
downloadTable <- function(metric, table) {
file = function(m) paste(m, Sys.Date(), '.csv', sep = '')
cont = function(table) write.csv(table, file)
downloadHandler(
filename = file(metric),
content = cont(table)
)
}
But when I run this as a Shiny app:
output$downloadRevenue <- downloadTable("revenue", revenue_table)
(Note revenue_table is a data frame)
Warning: Error in ==: comparison (1) is possible only for atomic and list types
86: force
85: map$set
84: self$downloads$set
83: shinysession$registerDownload
82: origRenderFunc
81: output$downloadRevenue
1: runApp
Something I struggle to follow in downloadHandler() is where it gets the variable 'file' from. It's not defined when I call it above in my first code block, yet it magically works. I think it's this piece that is causing my issues.
How can I make shiny::downloadHandler a custom function that takes two arguments, one 'metric', a string defining the name of the metric that the download table is for and then 2, the part that I think is tripping me up, the file?