2017-04-20 85 views
0

我目前正在研发一个基于R Shiny的Web应用程序,它基于动态创建的UI上的功能,包括渲染其他输入字段,即selectInputselectInputsinputId属性也是动态创建的,我无法预先定义创建的selectInputs的数量,因为它也会根据用户的输入而变化。注册事件处理程序动态添加selectInput

当我想对用户更改动态创建的selectInput中的选定值作出反应时,会出现此问题。然而

observeEvent(input$select_inputId, { ... }) 

,我不能抢先注册数目不详尚未指定inputIds的事件:通常情况下,如果selectInput是“静”,我会observeEvent注册。有没有可能将某种事件处理程序传递给selectInput或其他解决方案?

下面是代码动态创建我的用户界面的重要组成部分:

observeEvent(input$rate_criterion_select, { 
    output$rate_criterions_ratios <- renderUI({ 
    container <- tags$div() 
    for(i in seq(1, length(children_criterions))) { 
     container <- tagAppendChild(container, selectInput(
     inputId = paste(input$rate_criterion_select, i) 
     label = "" 
     choices = rates 
    ) 
    } 

    return(container) 
    }) 
}) 

编辑:下面你可以找到闪亮的应用程序的可重复的例子。解决方案是将用户提供的值存储在变量choices中。例如:如果用户选择3个输入来填充并相应地选择“一个”,“两个”和“三个”,则choices应该是矢量c("One","Two","Three");如果用户选择了2个输入来填充并选择“Two”,“Two” - choices应该是c("Two","Two")

server.R

library(shiny) 

# choices <- 

shinyServer(function(input, output) { 

    observeEvent(input$how_many, { 
    output$render_area <- renderUI({ 
     container <- tags$div() 
     for(i in seq(1, as.numeric(input$how_many))) { 
     container <- tagAppendChild(container, selectInput(
      inputId = paste("selection", i), 
      label = paste("Selection", i), 
      choices = c("One", "Two", "Three"), 
      selected = "One" 
     )) 
     } 

     return(container) 
    }) 
    }) 

}) 

ui.R

library(shiny) 

shinyUI(fluidPage(

    titlePanel("Example App"), 

    sidebarLayout(
    sidebarPanel(
     selectInput("how_many", "How many inputs do you want to fill?", c("1", "2", "3", "4", "5")) 
    ), 

    mainPanel(
     uiOutput("render_area") 
    ) 
) 
)) 
+0

请发布一个可重复的示例 - 其他人可以运行的完整应用的代码 –

+0

我刚刚添加了完整示例应用的代码,希望能够清楚地说明问题所在。 –

回答

0

这不是一个回答你的问题,但我可以在你的代码中看到一些奇怪的事情那不应该做。这里是你的代码的重写,我建议你使用作为起点:

ui <- fluidPage(
    titlePanel("Example App"), 

    sidebarLayout(
    sidebarPanel(
     numericInput("how_many", "How many inputs do you want to fill?", 1, 1, 5) 
    ), 

    mainPanel(
     uiOutput("render_area") 
    ) 
) 
) 

server <-function(input, output) { 

    output$render_area <- renderUI({ 
    lapply(seq(input$how_many), function(i) { 
     selectInput(
     inputId = paste("selection", i), 
     label = paste("Selection", i), 
     choices = c("One", "Two", "Three") 
    ) 
    }) 
    }) 

} 

shinyApp(ui,server) 
  • 取而代之的是选择下拉菜单有号码,然后不得不将它们转换成整数的,只用一个numericInput()
  • 您可以使用lapplt()创建并返回多个选择下拉列表,而不是使用for循环和tagAppendChild() - 这是过度冲击
  • 您不应该在input$how_many的观察者的内部定义您的output$render_areaoutput$render_area应该是顶级的。我建议对反应性阅读一些资源,因为这个代码暗示反应的误解(这是一个棘手的问题!)

同样,这不回答你的问题,但我希望它有助于在将来所有的闪亮代码。

+0

感谢您的更正,实际上我对Shiny和R总体来说是比较新的,我只知道非常基本的例子中的反应性。 –

相关问题