Joel Lahrman
Joel Lahrman

Reputation: 41

R Shiny - downloading a csv to the working directory

I’ve got a Shiny app in which I’d like to accomplish the following:

1) User presses a button

2) A data frame gets exported to a .csv, saved in either the working directory (with server.R and ui.R), or ideally one level down.

I want this to happen automatically, because eventually I’m going to connect it with a checkboxGroupboxInput to loop through the data and produce a set of filtered .csv.

Here is the closest I can currently get, with fileToDownload representing my data frame:

ui.R:

downloadButton("rptDownload", "Download Report"),

server.R:

output$rptDownload <- downloadHandler(
   filename = function() {
     paste(getwd(), '/rpt/test.csv',sep = '')
   },
   content = function(con) {
     write.csv(fileToDownload, file = file.path(con))
   }
 )

When I run this from a Chrome browser, it downloads to a .csv, but it gets named with what I want to be the file path as part of the name: C--Work-Project_A-Shiny_DB-rpt-test.csv. It regards the getwd() and /rpt/ as part of the name instead of the file path. It gets downloaded to my Downloads folder, not the current working directory.

Any suggestions on how to improve my code?

Note that I have tried incorporating some suggestions from other threads. Among others:

Shiny (R): Download selection in selectInput to local machine

Automatic multi-file download in R-Shiny

https://groups.google.com/forum/#!topic/shiny-discuss/MaN4-ia6wfk

But these seem to be moving me further away from accomplishing what I'm trying to do. Thanks for any assistance.

Upvotes: 4

Views: 3073

Answers (1)

adilapapaya
adilapapaya

Reputation: 4795

I think what you want is for the user to click a button and have shiny save the data to some folder which you specify. Is this correct?

If that's what you want, then create a button which, when clicked by the user, will just write.csv(<DF-to-write>, <filename-to-use>) or something along those lines.

No need to use downloadHandler. The downloadHandler function is specific to exporting the data: The user clicks on this button and your app exports the data for them. The reason the data shows up in your Download folder when you use it this way is because you've set up your browser to store all downloaded files to your Download directory.

If you want, you can have one button for SaveSelectedData and another button for DownloadSavedData.

  • SaveSelectedData will write.csv the df's of interest to your specified folder.

  • DownloadSavedData will export the data out to your user (you can't specify where it will get downloaded to on your user's system though -- that's dependent on their browser settings).

Also keep in mind that when running on the server, you'll need to make sure that Shiny has permissions to write to the folder you want it to save files to.

Upvotes: 1

Related Questions