如何依次添加新的选择来选择izeizeInput?

时间:2019-07-07 09:51:44

标签: r shiny

我是R和Shiny的新手,我正在尝试弄清楚如何允许用户一次将新的“选择”添加到选择列表中。例如如果用户一次上传一个数据集,那么所有数据集的名称将可以在选择列表中选择。

我已经完成了简单的版本(请参见下文),用户可以在列表中添加一个新的“选择”。但是当您继续添加新选择时,显然不会保存每个新选择。

我尝试添加多个新选项的尝试也在下面。

#### Simple working version of adding 1 new choice ####
choices <- c("x", "y", "z")

ui <- fluidPage(
    selectizeInput("choices","Choices", choices = choices, multiple = TRUE),
    textInput("new_choices", "New choices to add"),
    actionButton("add_choices", "Add new choices")
)

server <- function(input, output,session) {

    observeEvent(input$add_choices, {
        req(input$new_choices)
        choices <- c(choices, input$new_choices)
        updateSelectizeInput(session, "choices", choices = choices)
    })

}

shinyApp(ui = ui, server = server)



#### Not working version of sequentially adding new choices ####
choices <- c("x", "y", "z")

ui <- fluidPage(
    selectizeInput("choices","Choices", choices = choices, multiple = TRUE),
    textInput("new_choices", "New choices to add"),
    actionButton("add_choices", "Add new choices")
)

server <- function(input, output,session) {

    temp <- reactive({
        choices
    })

    update_choices <- function() {
        temp <- reactive({
            c(temp, input$new_choices)
        })
        return(temp)
    }

    observeEvent(input$add_choices, {
        req(input$new_choices)
        temp <- update_choices()
        updateSelectizeInput(session, "choices", choices = temp)
    })

}

shinyApp(ui = ui, server = server)

无效代码导致以下结果: 警告:as.vector中的错误:无法将类型“ closure”强制转换为类型“ list”的向量   [没有可用的堆栈跟踪]

1 个答案:

答案 0 :(得分:1)

只需在选项中添加反应性值

library(shiny)

ui <- fluidPage(
  selectizeInput("choices","Choices", choices = c(), multiple = TRUE),
  textInput("new_choices", "New choices to add"),
  actionButton("add_choices", "Add new choices")
)

server <- function(input, output,session) {

  values = reactiveValues()
  values$current_choices = c("x", "y", "z")

  observeEvent(input$add_choices, {
    req(input$new_choices)
    values$current_choices <- c(values$current_choices, input$new_choices)
  })

  observe({
    updateSelectizeInput(session, "choices", choices = values$current_choices, selected = input$choices)
  })

}

shinyApp(ui = ui, server = server)