Update Shiny's 'selectInput' dropdown with new values after uploading new data using fileInput

后端 未结 2 523
小鲜肉
小鲜肉 2020-12-19 12:11

I have a Shiny app that includes a number of dropdown selection boxes, the values of which are filled from reading an RDS file. The app also includes a fileInput function to

2条回答
  •  臣服心动
    2020-12-19 12:48

    to riff off of @PoGibas' answer, I needed to load multiple list values for an app, here is a similar application using reactiveValues and observeEvent :

    library(shiny)
    
    # save a dummy RDS for loading
    saveRDS(list(names=LETTERS,numbers=seq(10)),'dummy.rds')
    # define initial values
    myDataList <- list(names=c("Tom","Dick","Harry"), numbers=seq(5))
    
    ui <- shinyUI(
      fluidPage(
        fileInput("file1", "Choose file to upload", accept = ".rds"),
        selectInput("myNames","Names", ""),
        selectInput("myNumbers","Numbers", ""),
        tableOutput("contents")
      )
    )
    
    server <- function(input, output, session) {
    
      md <- reactiveValues(
        names = myDataList$names,
        numbers = myDataList$numbers
      )
    
      observeEvent(input$file1,{
          d <- readRDS(input$file1$datapath)
          for (n in names(d)){
            md[[n]] <- d[[n]]
          }
      })
    
      output$contents <- renderTable({
       data.frame(data = c(md$names,md$numbers))
      })
    
      observe({
        updateSelectInput(session, "myNames",
                          label = "myNames",
                          choices = md$names,
                          selected = md$names[1])
        updateSelectInput(session, "myNumbers",
                          label = "myNumbers",
                          choices = md$numbers,
                          selected = md$numbers[1])
      })
    }
    
    shinyApp(ui, server)
    

提交回复
热议问题