Ad

Csv File Upload At Start Of R Shiny App (quasi Placeholder File)

- 1 answer

With this code I can upload a csv file in my shiny app.

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose CSV File", accept = ".csv"),
      checkboxInput("header", "Header", TRUE)
    ),
    mainPanel(
      tableOutput("contents")
    )
  )
)

server <- function(input, output) {
  output$contents <- renderTable({
    file <- input$file1
    ext <- tools::file_ext(file$datapath)
    
    req(file)
    validate(need(ext == "csv", "Please upload a csv file"))
    
    read.csv(file$datapath, header = input$header)
  })
}

shinyApp(ui, server)

I would like to load a placeholder csv file say df.csv automatically at the start of my shiny app.

I this possible or do I have rethink my strategy?

Ad

Answer

In the server, we may use if/else to create the placeholder .csv while loading

server <- function(input, output) {
  output$contents <- renderTable({
    
    if(is.null(input$file1)) {
      
       dat <- read.csv(file.path(getwd(), "df.csv"))
    } else {
    file <- input$file1
    ext <- tools::file_ext(file$datapath)
    
    req(file)
      validate(need(ext == "csv", "Please upload a csv file"))
    
    dat <- read.csv(file$datapath, header = input$header)
    }
    
    dat
    
    })
}

shinyApp(ui, server)
Ad
source: stackoverflow.com
Ad