我尝试使用服务器中的数字变量作为 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)
根据您的用例,您可以使用例如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