服务器中的变量可以用作 SelectInput() 函数中的“选定”默认值吗?

问题描述 投票:0回答:1

我尝试使用服务器中的数字变量作为 Shiny 中“selectInput()”框的默认值,但无济于事。有两个选择框,第一个是固定的,但我希望第二个选择框的默认值由变量设置,我该如何实现这一点?我尝试以不同的方式使用 renderUI() 和 uniOutput() 但没有成功。

library(shiny) 

ui <- fluidPage(
  uiOutput("year22"),
  selectInput("y1", label = "Start Year: ", choices = c(1900: 2024), 
              width = 100, size = 3, selectize = FALSE),
  selectInput("y2", label = "End Year: ", choices = c(1900: 2024),
              width = 100, size = 3, selected = year22, selectize = FALSE))

server <- function (input, output, session) {
    output$year22 <- renderUI({
      1963 #For simplicity I just included a number here instead of code, but I would 
           #like to use the variable 'year22' for the default value in the second 
           #selection box above
    })
}
shinyApp(ui, server)
r shiny selectinput
1个回答
0
投票

根据您的用例,您可以使用例如a

reactive
存储
year22
的值,然后使用
updateSelectInput
observe
r 设置第二个
selected=
selectInput
值:

library(shiny)

ui <- fluidPage(
  selectInput("y1",
    label = "Start Year: ", choices = c(1900:2024),
    width = 100, size = 3, selectize = FALSE
  ),
  selectInput("y2",
    label = "End Year: ", choices = c(1900:2024),
    width = 100, size = 3, selected = NULL, selectize = FALSE
  )
)

server <- function(input, output, session) {
  year22 <- reactive({ 1963 })
  observe({
    updateSelectInput(
      inputId = "y2",
      selected = year22()
    )
  })
}
shinyApp(ui, server)
#> 
#> Listening on http://127.0.0.1:7692

© www.soinside.com 2019 - 2024. All rights reserved.