I am trying to use a numerical variable from the server as the default value for the "selectInput()" box in Shiny to no avail. There are two selection boxes, the first one is fixed, but I want the default value for the second one to be set by a variable, how can I achieve this? I tried using renderUI() and uniOutput() in different ways with no success.
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)
Depending on your use case you can use e.g. a reactive
to store the value for year22
, then use updateSelectInput
and an observe
r to set the selected=
value for the second 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
UPDATE I can't reproduce the issue you reported in your comments. In the code below I added a textOutput
to the code which outputs the value selected in the second selectInput
and which shows that the input$y2
contains the selected value and no reversion of the selected=
value to 1963.
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
),
textOutput(
"end_year"
)
)
server <- function(input, output, session) {
year22 <- reactive({
1963
})
observe({
updateSelectInput(
inputId = "y2",
selected = year22()
)
})
output$end_year <- renderText({
input$y2
})
}
shinyApp(ui, server)