lapply函数在RShiny中的observeEvent周围使用numericInput参数

时间:2017-12-05 14:03:15

标签: r lapply shiny

我想创建许多相互连接的多个选择输入。换句话说:如果在其中一个选择输入中选择了一个项目,我希望它从其他选择输入中消失。选择。另外,我希望选择输入的数量对应于数字输入中选择的数字。

以下示例正在运行。我留下的唯一问题是在以下一行:

  X = 1:100, ####### QUESTION HERE

而不是1:100,我想放一些像1:输入$ ui_number但是我在R中有以下错误:

 Error in .getReactiveEnvironment()$currentContext() :  Operation not allowed without an active reactive context.

如果我把"反应"或者"观察"在lapply周围运行,observeEvent不再起作用了。对我来说有什么诀窍吗?

感谢您的帮助!

 modalities <- LETTERS[1:10]

 library(shiny)

 app <- shinyApp(
   ui = tabPanel("Change modalities",
            numericInput("ui_number", label="Number of modalities",min = 1, max = 4, value=3),
            uiOutput("renderui")
   ),


   server = function(input, output, session) {


     output$renderui <- renderUI({
       output = tagList()
       for(i in 1:input$ui_number){
         output[[i]] = tagList()
         output[[i]][[1]] = selectizeInput(paste0("ui_mod_choose",i), label=paste0("Modality ",i),choices=modalities, multiple = TRUE)
  }
  return(output)
})


 lapply(
  X = 1:100, ####### QUESTION HERE
  FUN = function(j){
    observeEvent({
      input[[paste0("ui_mod_choose",j)]]
    },
    {
      sapply(1:input$ui_number,function(i){
        vecteur <- do.call(c,lapply((1:input$ui_number)[-i],function(i){input[[paste0("ui_mod_choose",i)]]}))
        updateSelectizeInput(session,paste0("ui_mod_choose",i),choices=  modalities[!modalities %in% vecteur],selected = input[[paste0("ui_mod_choose",i)]])
      })
    },
    ignoreNULL = FALSE)

  }
)


observeEvent({
  input$ui_num
},
{
  sapply(1:nput$ui_num,function(i){ 
    updateSelectizeInput(session,paste0("ui_mod_choose",i),choice= modalities,selected=NULL)
       })
     }
     )

   }

 )
 runApp(app)

1 个答案:

答案 0 :(得分:1)

您可以使用一个observe()而不是多个observeEvent()

library(shiny)

modalities <- LETTERS[1:10]

ui = tabPanel("Change modalities",
              numericInput("ui_number", label = "Number of modalities",
                           min = 1, max = 4, value = 3),
              uiOutput("renderui"))

server = function(input, output, session) {

  # Generate modalities select lists
  output$renderui <- renderUI({
    output = tagList()
    for (i in seq_len(input$ui_number)) {
      output[[i]] = selectizeInput(paste0("ui_mod_choose", i), 
                                   label = paste0("Modality ", i),
                                   choices = modalities, multiple = TRUE)
    }
    return(output)
  })

  # Remove selected modalities from other select lists
  observe({
    n <- isolate(input$ui_number)
    for (i in seq_len(n)) {
      vecteur <- unlist(lapply((1:n)[-i], function(i) 
        input[[paste0("ui_mod_choose",i)]]))
      updateSelectizeInput(session, paste0("ui_mod_choose",i),
                           choices = setdiff(modalities, vecteur),
                           selected = input[[paste0("ui_mod_choose",i)]])
    }
  })

}

runApp(shinyApp(ui, server))