library(shiny)
library(readr)
<- read_csv("./data/estate.csv")
estate
<- fluidPage(
ui tableOutput("estate")
)
<- function(input, output, session) {
server $estate <- renderTable({
outputhead(estate)
})
}
shinyApp(ui, server)
File Upload
Learning Objectives
- Learn how to upload datasets for use in the Shiny App.
- Chapter 8 of Mastering Shiny.
- Shiny Cheatsheet.
- Optional Resources
Static Dataset Upload
If your Shiny app is designed to analyze only a single dataset (which might contain multiple files), then you should upload it at the start of the app.
- Create a new “data” folder in your app.
- Place all data files in the “data” folder.
- Read in these data at the start of the app.
New data folder:
Put data in data folder:
Load data at beginning of app:
When a Shiny app is run, the location of “app.R” is the location of the working directory, so all file upload/download must be done from that location as a reference point.
Interactive File Upload
Use the
fileInput()
function in the UI to allow users to choose the source of the dataset.library(shiny) <- fluidPage( ui fileInput("file", "Where is the file?") ) <- function(input, output, session) { server } shinyApp(ui, server)
In the
server()
function, the element ininput
(in this caseinput$file
) is a data frame with the following columns:name
: The name of the file on the user’s computer.size
: The size of the file in bytes. Shiny only accepts files up to 5 MB. To increase it to 10 MB, type the following somewhere in “app.R”:options(shiny.maxRequestSize = 10 * 1024^2)
type
: The file extension (text/csv, text/plain etc)datapath
: A temporary path file.
Useful arguments:
accept
: What file extensions are acceptable (".csv"
,".txt"
, etc).buttonLabel
: Customize label of button.multiple
: Can the user upload multiple files?
Example Shiny App
library(shiny) <- fluidPage( ui fileInput("upload", NULL, buttonLabel = "Upload...", multiple = TRUE), tableOutput("files") ) <- function(input, output, session) { server $files <- renderTable(input$upload) output } shinyApp(ui = ui, server = server)
General strategies:’
- Place code to read in files inside a
reactive()
call. - Inside the reactive call, always use
req()
to wait to read in data until the path is available. - Save the read-in files as reactive elements.
- In the server function, you use the
datapath
value as thepath
argument inread_csv()
,read_tsv()
,readRDS()
, etc.
library(shiny) library(readr) <- fluidPage( ui fileInput("file", "What file?", accept = "text/csv"), tableOutput("head") ) <- function(input, output, session) { server <- reactive({ data req(input$file) read_csv(input$file$datapath) }) $head <- renderTable({ outputhead(data(), 5) }) } shinyApp(ui, server)
- Place code to read in files inside a