如何在一个向量中将多个输入组合成闪亮的。输入数量取决于用户的选择

时间:2019-06-14 14:32:24

标签: r shiny

我正在尝试创建一个UI,用户可以在其中选择一些对象(尽可能多地选择它们)以及它们各自的权重。权重输入字段仅在存在多个对象时出现,并随着用户选择更多对象而增加。这部分已经起作用。

我需要的是一个向量,其中保存了w1w2等中保存的所有权重。

我尝试使用for循环并通过get()函数进行应用,但是无法访问input$w1input$w2等。

library(shiny)

# Create list of objects
object_list <- vector()
object_list <- paste0("O_", 1:10)
names(object_list) <- paste("Object", 1:10)

ui <- dashboardPage(
  dashboardHeader(title = "Dynamic UI"),
  dashboardSidebar(
    width = 700,
    fluidRow(
      column(7, selectInput("chosen_objects", "Chosen objects", choices = object_list, multiple = TRUE, width = "100%")),
      column(5, uiOutput("weights"))
    )
  ),
  dashboardBody(
    fluidPage(tabBox(width=2500,
                     tabPanel(
                       title = "Table"
                      )
    )
    )
  )
)

server <- function(input,output) {

  objects_number <- reactive({length(input$chosen_objects)})

  output$weights <- renderUI({
    if (is.na(objects_number()) | objects_number() <= 1)
      return(NULL)
    lapply(1:objects_number(), function(i) {
      id <- paste0("w", i)
      textInput(id, paste("Weight of", input$chosen_objects[i]), value = input[[id]], width = "50%", placeholder = "%")
    })
  })

}

shinyApp(ui, server)

有没有一种方法可以将动态输入收集到一个矢量或列表中?

1 个答案:

答案 0 :(得分:1)

我进行了一些更改,并且根据您的代码,我认为您有足够的能力亲自查看和获取它们。让我知道您是否有任何疑问-

library(shiny)

# Create list of objects
object_list <- vector()
object_list <- paste0("O_", 1:10)
names(object_list) <- paste("Object", 1:10)

ui <- dashboardPage(
  dashboardHeader(title = "Dynamic UI"),
  dashboardSidebar(
    width = 700,
    fluidRow(
      column(7, selectInput("chosen_objects", "Chosen objects", 
                     choices = object_list, multiple = TRUE, width = "100%")),
      column(5, uiOutput("weights"))
    )
  ),
  dashboardBody(
    fluidPage(tabBox(width=2500,
                     tabPanel(
                       title = "Table",
                       verbatimTextOutput("weight_output")
                      )
    )
    )
  )
)

server <- function(input,output) {

  objects_number <- reactive({length(input$chosen_objects)})

  output$weights <- renderUI({
    if (is.na(objects_number()) | objects_number() <= 1)
      return(NULL)
    lapply(gsub("[A-Z]+_", "", input$chosen_objects), function(i) {
      id <- paste0("w", i)
      textInput(id, paste("Weight of", paste0("O_", i)), 
                value = NULL, width = "50%", placeholder = "%")
    })
  })

  output$weight_output <- renderPrint({
    req(input$chosen_objects)
    sapply(paste0("w", gsub("[A-Z]+_", "", input$chosen_objects)), function(a) input[[a]])
  })

}

shinyApp(ui, server)