DCB
DCB

Reputation: 117

R-shiny download button explained

I'm trying to get my head arround the following. Trying to understand the workings of R-shiny more deeply.

In creating a download button, R shiny advises to use the following code-snipped:

output$downloadData <- downloadHandler(
  filename = function() {
    paste('data-', Sys.Date(), '.csv', sep='')
  },
  content = function(con) {
    write.csv(data, con)
  }
)

A filename is created with the function named: filename. And, content is written using a function created named content.

The content function takes con as input. This, in my understanding, just sets the filename/filepath parameter of the write.csv function inside the content function.

Why is the filename (function) not used as an input argument, and why does this nontheless sets the path for the filename/filepath argument in the conent function/ write.csv?

Upvotes: 0

Views: 1489

Answers (1)

Gregor de Cillia
Gregor de Cillia

Reputation: 7665

Actually, the current documentation of downloadHandler uses the following in the examples

content = function(file) {
  write.csv(data, file)
}

The documentation of the content argument also mentions file paths, not connections

content
A function that takes a single argument file that is a file path (string) of a nonexistent temp file, and writes the content to that file path. (Reactive values and functions may be used from this function.)

The reason both filename and content are functions is so they can both change based on the state your application is currently in. If you want content to be dependent on the input your user, you might use for examle this.

content = function(file) {
  write.csv(get_current_data(input$choose_dataset), file)
}

The same is true for filename

filename = function() { paste0(input$choose_dataset, ".csv") }

Upvotes: 1

Related Questions