How to extract the values of dynamically generated

2019-07-14 00:01发布

问题:

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)