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 tofileInput()
to limit input types.- browser doesn’t always enforce, so make sure to
validate()
- browser doesn’t always enforce, so make sure to
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)
})
}