我试图根据用户的输入为shiny::numericInput()动态设置shiny::numericInput()参数。
下面的两个代码块都将运行,但它们无法设置动态初始值。
块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)块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)我希望shiny::numericInput的初始值发生如下变化:
当用户选择"1“进行识别时,初始值为100:

当用户选择"2“进行识别时,初始值为227:

其背后的想法是根据输入的标识向用户建议一个适当的初始值。
我猜想问题可能与shiny::verbatimTextOutput("numberOut")有关,但我不知道如何呈现一个简单的数字值以传递给shiny::numericInput的value参数。
有什么想法吗?
非常感谢。
发布于 2021-07-27 20:07:35
一种方法是使用renderUI并在服务器端进行计算:
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)])
})
})另一种方法是将输入留在UI端,并在observeEvent中使用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)])
})
}) https://stackoverflow.com/questions/68550960
复制相似问题