使用 fileInput 上传新数据后,使用新值更新 Shiny 的“selectInput”下拉列表

jan*_*ade 5 r shiny

我有一个 Shiny 应用程序,其中包含许多下拉选择框,其中的值是通过读取 RDS 文件填充的。该应用程序还包括一个用于上传新数据的 fileInput 函数。如何更改下拉框中的值以反映新数据?目前我可以看到数据已上传,但旧数据仍保留在下拉列表中。

应该上传的数据使用

saveRDS( data.frame(names=c("Jill","Jane","Megan")),"myDataFrame.rds")
Run Code Online (Sandbox Code Playgroud)

在我的 app.R 文件中,我首先定义数据的“默认”值:

myDataFrame <- data.frame(names=c("Tom","Dick","Harry"))
Run Code Online (Sandbox Code Playgroud)

我的内容app.R如下:

library(shiny)
ui <- shinyUI(
 fluidPage(
  fileInput('file1', 'Choose file to upload',accept = ".rds"),
  selectInput("myNames","Names",myDataFrame$names),
  tableOutput('contents')
 )
)

server <- shinyServer(function(input, output) {
  output$contents <- renderTable({
    inFile <- input$file1
    if (is.null(inFile)) { return(myDataFrame) }
    readRDS(inFile$datapath)
  })
  })
Run Code Online (Sandbox Code Playgroud)

应用程序的初始视图符合预期:下拉列表和表格都包含“默认”名称。上传包含新数据框的 RDS 文件后,表格会发生变化(这是我正在寻找的内容),但下拉值不会发生变化。我怎样才能使后者发生?

PoG*_*bas 5

我添加了myData必须用于 table 的反应性对象contents,但更重要的是更新selectInput(检查observeupdateSelectInput部分)中的选择。

library(shiny)

ui <- shinyUI(
    fluidPage(
        fileInput("file1", "Choose file to upload", accept = ".rds"),
        selectInput("myNames","Names", ""),
        tableOutput("contents")
    )
)

server <- function(input, output, session) {

    myData <- reactive({
        inFile <- input$file1
        if (is.null(inFile)) {
            d <- myDataFrame
        } else {
            d <- readRDS(inFile$datapath)
        }
        d
    })

    output$contents <- renderTable({
        myData()
    })

    observe({
         updateSelectInput(session, "myNames",
                           label = "myNames",
                           choices = myData()$names,
                           selected = myData()$names[1])
    })

}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)