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

我与影子孤独终老i 提交于 2020-01-02 07:31:30

问题


I am creating a shiny app which will generate the score for clients based on their different features. In my shiny app, I have provided the checkboxGroupInput to select the required features. Based on the selected features app will dynamically add numericInput to the web ui so that user can assign the weight for the selected features and further the weights will be used in score calculation. I have tried different ways to get the selected features and wanted to save them in a vector. So that I can use the elements of the vector to calculate the score. Please someone show me a solution to save the selected features from checkboxGroupInput in a vector and based on that vector access the dynamically created numbericInput values.

Code Snippet

# Select variables to determine the credit worthyness
    checkboxGroupInput(

      inputId = "selected_var",

      label = "Choose variables:",

      choices = c(
        "R" = "r",
        "F" = "f",
        "M" = "m"
        ),

      selected = c("r","f"))
  )

server <- function(input, output) {

  output$weights_input <- renderUI({ 

req(input$selected_var)
req(input$weights)


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)
})
  })

回答1:


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)


来源:https://stackoverflow.com/questions/50795355/how-to-extract-the-values-of-dynamically-generated-inputs-in-shiny

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