9.2 Uploading data

There are 2 things to note about uploading a data set.

  • Use req(input$file) to make sure file is uploaded before code runs.
  • Use accept argument to fileInput() to limit input types.
    • browser doesn’t always enforce, so make sure to validate()

Example of uploading a data set and validating file type (from book):

ui <- fluidPage(
  fileInput("file", NULL, accept = c(".csv", ".tsv")),
  numericInput("n", "Rows", value = 5, min = 1, step = 1),
  tableOutput("head")
)

server <- function(input, output, session) {
  data <- reactive({
    req(input$file)
    
    ext <- tools::file_ext(input$file$name)
    switch(ext,
      csv = vroom::vroom(input$file$datapath, delim = ","),
      tsv = vroom::vroom(input$file$datapath, delim = "\t"),
      validate("Invalid file; Please upload a .csv or .tsv file")
    )
  })
  
  output$head <- renderTable({
    head(data(), input$n)
  })
}

9.2.1 Observe this in action

  • Check out the app-upload.R example

9.2.2 Use a break-point to observe what’s going on here

  • Add a breakpoint before the switch() function.
    • Examine input$upload
    • Examine input$file$datapath object
    • Examine ext
    • Import data in the interactive debugger
  data <- reactive({
    req(input$upload)
    
    ext <- tools::file_ext(input$upload$name)
#> Add a breakpoint here    
    switch(ext,
           csv = vroom::vroom(input$upload$datapath, delim = ","),
           tsv = vroom::vroom(input$upload$datapath, delim = "\t"),
           validate("Invalid file; Please upload a .csv or .tsv file")
           )
    
  })