我有一个 Shiny 应用程序,其中包含许多下拉选择框,其中的值是通过读取 RDS 文件填充的。该应用程序还包括一个用于上传新数据的 fileInput 函数。如何更改下拉框中的值以反射(reflect)新数据?目前我可以看到数据已上传,但旧数据仍保留在下拉列表中。
应该上传的数据使用
saveRDS( data.frame(names=c("Jill","Jane","Megan")),"myDataFrame.rds")
在我的 app.R 文件中,我首先定义数据的“默认”值:
myDataFrame <- data.frame(names=c("Tom","Dick","Harry"))
我的内容
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)
})
})
应用程序的初始 View 符合预期:下拉列表和表格都包含“默认”名称。上传包含新数据框的 RDS 文件后,表格会发生变化(这是我正在寻找的内容),但下拉值不会发生变化。我怎样才能使后者发生?
最佳答案
我添加了 react 对象 myData
您必须用于表 contents
,但更重要的是更新 selectInput
中的选择(检查 observe
和 updateSelectInput
部分)。
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)
关于r - 使用 fileInput 上传新数据后,使用新值更新 Shiny 的 'selectInput' 下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46346917/