rr-markdownflexdashboard

Download a dataframe as csv in Flex Dashboard


I have a flex dashboard that is designed to share as a stand alone html file. What I would like to do is allow my reader to download some of the raw data sets used in the report. I can't use a shiny download button because it won't work in static html file.

I had a variety of thoughts on this:

  palette <- monkeyr::get_heat_palette(6)

  myData <- data.frame(
    Name = c("Alice", "Bob", "Charlie"),
    Age = c(25, 30, 22)
  )

  flexdashboard::valueBox(paste0("Device Data"),
                          icon = "fa-tablet",
                          href = paste0(write.csv(myData, row.names = FALSE)),
                          # color = ifelse(below_18 > 0.40, "warning", "primary"),
                          color = palette[6])

Obviously doesn't work, but is there a way to modify the href so it will?

This works:

<a href="data:text/csv;charset=utf-8,%EF%BB%BFYOUR_CSV_DATA_HERE" download="my_data.csv">

But all my efforts to replace the fixed text with the contents of the csv have failed:

<a href="data:text/csv;charset=utf-8,%EF%BB%BF <%= paste0(csv_content) %> " download="my_data.csv">
  Download CSV File
</a>

One last ditch try! Now I'm genuinely perplexed as to why this doesn't work. It one of the ugliest pieces of code I've ever written, but why is the paste0 function not doing what I expect?

  myData <- data.frame(
    Name = c("Alice", "Bob", "Charlie"),
    Age = c(25, 30, 22)  
  )

  link1 <- paste0('<a href="data:text/csv;charset=utf-8,%EF%BB%BF', write.csv(myData, row.names = FALSE), '" download="my_data.csv">')
  link2 <- "  Download My CSV"
  link3 <- "</a>"

I then print these out. The link code works fine, but the contect isn't there!

If I assign the value to link1 and print it out, I see this:

> link1
[1] "<a href=\"data:text/csv;charset=utf-8,%EF%BB%BF\" download=\"my_data.csv\">"

Where has the csv content gone???


Solution

  • There are two ways: