How to extract the values of dynamically generated inputs in Shiny?

别等时光非礼了梦想. 提交于 2019-12-06 01:04:37

You can get the value of a dynamically generated input as

input[[paste0(input$selected_var[i],"_weight")]]`

while you can get the array with selected check boxes simply with input$selected_var.

A working example is given below, I hope this helps!

library(shiny)

ui <- fluidPage(
  checkboxGroupInput(
    inputId = "selected_var",
    label = "Choose variables:",
    choices = c(
      "R" = "r",
      "F" = "f",
      "M" = "m"
    ),
    selected = c("r","f")
  ),
  uiOutput('weights_input'),
  textOutput('score')
)

server <- function(input, output) {

  output$weights_input <- renderUI({ 
    req(input$selected_var)
    lapply(1:length(input$selected_var), function(i) {
      numericInput(inputId = paste0(input$selected_var[i],"_weight"), label = input$selected_var[i], min = 0, max = 1, value = 0)
    })
  })

    output$score <- renderText({
      req(input$selected_var)
      selected = input$selected_var
      values = sapply(1:length(input$selected_var), function(i) {
        req(input[[ paste0(input$selected_var[i],"_weight")]]);input[[ paste0(input$selected_var[i],"_weight")]]
      })
      values = setNames(values,selected)
      paste0('Input: [', paste(names(values), values, sep = ":", collapse = ", "), ']. The sum of the values is ', sum(values))

  })
}

shinyApp(ui,server)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!