Home > Mobile >  setting a default datatable and replacing it with a suitable file type in r shiny
setting a default datatable and replacing it with a suitable file type in r shiny

Time:11-17

I would like to have a shiny app that, when run for the first time, displays a dataframe defined as a template, and then the user can upload a new one (in csv only) that replaces the current one. Therefore, in case the user imports a file of the wrong type, it produces a message instead. Here is my code, which results in an error, and I don't know why it doesn't work

library(shiny)
library(DT)
library(dplyr)


library(shiny)

ui <- fluidPage(
  
  fileInput("upload", NULL, accept = c(".csv")),
  tableOutput("head")
  
)

server <- function(input, output, session) {
  
  rv <- reactiveValues(
    dataframe = NULL
  )
  observe({
    
    
    if(is.null(rv$dataframe)){
  
      dataFrameFile <- reactive({
        
        df <- data.frame(
          x = seq(1:12),
          y = rnorm(12))
        
        rv$dataframe <- datatable(df)
        
        return(rv$dataframe)
        
      })
      
    } else {
      
      dataFrameFile <- reactive({
        req(input$upload)
        
        ext <- tools::file_ext(input$upload$name)
        rv$dataframe <- switch(ext,
               csv =  read.csv(input$upload$datapath),
               validate(" Please upload a .csv file")
        )
      })
      
    }
    
  })
  
  output$head <- renderDT({
  
    datatable(dataFrameFile())
  })
}

shinyApp(ui, server)

CodePudding user response:

A few corrections/simplifications:

  • Used DTOutput instead of tableOutput to correspond to renderDT
  • directly initialized rv
  • put the validate in the renderDT
library(shiny)
library(DT)
library(dplyr)


library(shiny)

ui <- fluidPage(
  
  fileInput("upload", NULL, accept = c(".csv")),
  DTOutput("head")
  
)

server <- function(input, output, session) {
  
  rv <- reactiveValues(
    dataframe = data.frame(
      x = seq(1:12),
      y = rnorm(12))
  )
 
      observe({
        req(input$upload)
        ext <- tools::file_ext(input$upload$name)
        rv$dataframe   <- switch(ext,
                                 csv =  read.csv(input$upload$datapath),
                                                NULL)
      })
      

  output$head <- renderDT({
    validate(need(!is.null(rv$dataframe)," Please upload a .csv file"))
    rv$dataframe
  })
}

shinyApp(ui, server)

enter image description here

  • Related