如何在Shiny中提取动态生成的输入值?

时间:2018-06-11 10:12:33

标签: r shiny shiny-server

我正在创建一个闪亮的应用程序,它将根据客户的不同功能为客户生成分数。在我的闪亮应用中,我提供了checkboxGroupInput来选择所需的功能。基于所选功能,应用程序将动态地将numericInput添加到web ui,以便用户可以为所选功能分配权重,并且权重将用于分数计算。我尝试了不同的方法来获取所选的功能,并希望将它们保存在矢量中。这样我就可以使用向量的元素来计算分数。请有人向我展示一个解决方案,将矢量中的checkboxGroupInput保存所选功能,并根据该矢量访问动态创建的numbericInput值。

代码段

# 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 个答案:

答案 0 :(得分:2)

您可以将动态生成的输入的值作为

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

虽然只需使用input$selected_var就可以使用选中的复选框获取数组。

下面给出了一个工作实例,我希望这有帮助!

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)