Created
February 24, 2018 03:26
-
-
Save cecilialee/470ec755a2e5378340ea9a554d12d9b7 to your computer and use it in GitHub Desktop.
Download files function in Shiny. #r #shiny
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
library(dplyr) | |
library(readr) | |
load(url("http://s3.amazonaws.com/assets.datacamp.com/production/course_4850/datasets/movies.Rdata")) | |
# UI | |
ui <- fluidPage( | |
sidebarLayout( | |
# Input(s) | |
sidebarPanel( | |
# Select filetype | |
radioButtons(inputId = "filetype", | |
label = "Select filetype:", | |
choices = c("csv", "tsv"), | |
selected = "csv"), | |
# Select variables to download | |
checkboxGroupInput(inputId = "selected_var", | |
label = "Select variables:", | |
choices = names(movies), | |
selected = c("title")) | |
), | |
# Output(s) | |
mainPanel( | |
HTML("Select filetype and variables, then hit 'Download data'."), | |
downloadButton("download_data", "Download data") | |
) | |
) | |
) | |
# Server | |
server <- function(input, output) { | |
# Download file | |
output$download_data <- downloadHandler( | |
filename = function() { | |
paste0("movies.", input$filetype) | |
}, | |
content = function(file) { | |
if(input$filetype == "csv"){ | |
write_csv(movies %>% select(input$selected_var), file) | |
} | |
if(input$filetype == "tsv"){ | |
write_tsv(movies %>% select(input$selected_var), file) | |
} | |
} | |
) | |
} | |
# Create a Shiny app object | |
shinyApp(ui = ui, server = server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment