使用文件输入上载新数据后,使用新值更新闪亮的选择输入下拉列表 [英] Update Shiny's 'selectInput' dropdown with new values after uploading new data using fileInput

查看:11
本文介绍了使用文件输入上载新数据后,使用新值更新闪亮的选择输入下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个闪亮的应用程序,其中包括许多下拉选择框,其中的值是通过读取RDS文件来填充的。这款应用程序还包括一个上传新数据的文件输入功能。如何更改下拉框中的值以反映新数据?目前我可以看到数据已上载,但旧数据仍保留在下拉列表中。

应上载的数据使用

保存到文件中
saveRDS( data.frame(names=c("Jill","Jane","Megan")),"myDataFrame.rds")

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

myDataFrame <- data.frame(names=c("Tom","Dick","Harry"))

Myapp.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)
  })
  })
应用程序的初始视图与预期不谋而合:下拉列表和表都包含"默认"名称。在上传包含新数据帧的RDS文件时,表发生了变化(这正是我所寻找的),但下拉列表的值没有变化。我如何才能实现后一种情况?

推荐答案

我添加了必须用于表contents的反应对象myData,但更重要的是更新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)

这篇关于使用文件输入上载新数据后,使用新值更新闪亮的选择输入下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆