Home > database >  csv file upload at start of r shiny app (quasi placeholder file)
csv file upload at start of r shiny app (quasi placeholder file)

Time:02-14

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?

CodePudding user response:

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)
  • Related