I'm trying to make the value
argument for shiny::numericInput()
dynamic, based on input from a user.
Both code chunks below will run, but they fail to set a dynamic initial value.
Chunk 1:
idOptions <- c("1","2","3")
ui <- shiny::fluidPage(
shiny::selectInput(inputId = "idSelection", "Identification: ", idOptions),
shiny::numericInput("num", "Number associated with id:", value=shiny::verbatimTextOutput("numberOut")),
)
server <- function(input, output) {
df <- data.frame(id = c("1","2","3"), number = c(100,227,7))
output$numberOut <- shiny::renderText({ input$idSelection })
}
shiny::shinyApp(ui, server)
Chunk 2:
idOptions <- c("1","2","3")
ui <- shiny::fluidPage(
shiny::selectInput(inputId = "idSelection", "Identification: ", idOptions),
shiny::numericInput("num", "Number associated with id:", value=shiny::verbatimTextOutput("numberOut")),
)
server <- function(input, output) {
df <- data.frame(id = c("1","2","3"), number = c(100,227,7))
dfReactive <- shiny::reactive({
dataOut <- df %>%
dplyr::filter(., id %in% input$idSelection)
return(dataOut)
})
shiny::observe({
output$numberOut <- shiny::renderText({
return(dfReactive()$number)
})
})
}
shiny::shinyApp(ui, server)
I want the initial value for shiny::numericInput
to change like so:
When the user selects "1" for Identification, the initial value is 100:
When the user selects "2" for Identification, the initial value is 227:
The idea behind this is to have an appropriate initial value suggested to the user based on the identification of the input.
I'm guessing the problem might be with shiny::verbatimTextOutput("numberOut")
, but I don't know a way to render a simple numeric value to pass into the value
argument of shiny::numericInput
.
Any thoughts?
Thanks much.
One way would be to use renderUI
and do the computation on the server side:
idOptions <- c("1","2","3")
shiny::shinyApp(
ui = shiny::fluidPage(
shiny::selectInput(inputId = "idSelection", "Identification: ", idOptions),
shiny::uiOutput("num")
),
server = function(input, output) {
df <- data.frame(id = c("1","2","3"), number = c(100,227,7))
output$num <- shiny::renderUI({
shiny::numericInput("num",
"Number associated with id:",
value = df$number[as.numeric(input$idSelection)])
})
})
The alternative is to leave the input on the UI side and use updateNumericInput
inside an observeEvent
:
idOptions <- c("1","2","3")
shiny::shinyApp(
ui = shiny::fluidPage(
shiny::selectInput(inputId = "idSelection",
"Identification: ",
idOptions),
shiny::numericInput("num",
"Number associated with id:",
value = NULL)
),
server = function(input, output, session) {
df <- data.frame(id = c("1","2","3"),
number = c(100,227,7))
observeEvent(input$idSelection, {
updateNumericInput(session,
inputId = "num",
value = df$number[as.numeric(input$idSelection)])
})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.