【问题标题】:How to create a UI in Shiny from a for loop whose length is based on numeric input?如何从长度基于数字输入的 for 循环在 Shiny 中创建 UI?
【发布时间】:2019-03-21 16:05:27
【问题描述】:

作为这个例子的扩展:

https://shiny.rstudio.com/gallery/creating-a-ui-from-a-loop.html

假设您希望 for 循环的长度由数字输入确定。例如,扩展链接示例(仅使用它的第二部分):

ui <- fluidPage(
  title = 'Creating a UI from a dynamic loop length',
  sidebarLayout(
    sidebarPanel(
      # Determine Length of Loop
      numericInput(inputId = "NumLoop", "Number of Loops", value = 5, min = 1, max = 5, step = 1)
    ),
    mainPanel(
      # UI output
      lapply(1:input.NumLoop, function(i) {
        uiOutput(paste0('b', i))
      })
    )
  )
)

server <- function(input, output, session) {
  reactive({
    lapply(1:input$NumLoop, function(i) {
      output[[paste0('b', i)]] <- renderUI({
        strong(paste0('Hi, this is output B#', i))
      })
    })
  })
}

shinyApp(ui = ui, server = server)

据我所知,代码有两个问题:

在 UI 中,我不知道如何在 UI 输出的 for 循环中合法地使用来自 NumLoop 的输入。我尝试了conditionalPanel 函数,但没有成功。

在服务器中,一旦我将循环放在 reactive 函数后面以使用 input$NumLoop,我就无法再访问 UI 中的那些 renderUI 输出。

任何关于如何解决这些问题的想法都将不胜感激。

【问题讨论】:

    标签: r shiny shiny-reactivity


    【解决方案1】:

    这应该可以解决问题,根据@Dean,是的,第二个renderUI 不应该在那里

    library(shiny)
    
    ui <- fluidPage(
      title = 'Creating a UI from a dynamic loop length',
      sidebarLayout(
        sidebarPanel(
          # Determine Length of Loop
          numericInput(inputId = "NumLoop", "Number of Loops", value = 5, min = 1, max = 10, step = 1)
        ),
        mainPanel(
          # UI output
          uiOutput('moreControls')
        )
      )
    )
    
    server <- function(input, output, session) {
    
      output$moreControls <- renderUI({
        lapply(1:input$NumLoop, function(i) {
          strong(paste0('Hi, this is output B#', i),br())
        })
      })
    
    }
    
    shinyApp(ui = ui, server = server)
    

    【讨论】:

    • 效果很好,也喜欢演示!
    • output[[paste0('b', i)]] &lt;- renderUI({ 行是不必要且不正确的。在 lapply 中你只需要strong(paste0('Hi, this is output B#', i))(或者如果你想确保每一个都放在一个新的行上,你可以将它包装在div() 中)
    猜你喜欢
    • 2021-08-20
    • 1970-01-01
    • 2017-10-08
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 2023-04-01
    • 2023-02-22
    相关资源
    最近更新 更多