【问题标题】:How to avoid a for-loop when creating several UI elements based on user input (a vector) in shiny R在闪亮的R中基于用户输入(向量)创建多个UI元素时如何避免for循环
【发布时间】:2017-04-19 17:42:52
【问题描述】:

我想在我闪亮的应用程序中避免臭名昭著的 for 循环,但到目前为止我还没有找到解决方案。这是我的第一个真正闪亮的项目,任何意见都非常感谢。

我的场景是:用户提供一个数据框。然后,该应用程序会为每一列生成一个下拉菜单。 (稍后这将用于决定在线性模型中是否应将列视为因子、协变量或忽略)

我目前的方法是使用 for 循环和 insertUI 函数:

ui.R:

library(shiny)
shinyUI(
  fluidPage(
    actionButton("ADD","ADD")
  )
)

server.R

library(shiny)
opts <- c("A","B")
shinyServer(function(input, output) {
  for(i in 1:length(mtcars)){
  insertUI(
        selector = "#ADD",
        where="afterEnd",
      ui=selectInput(paste(names(mtcars[i]),"sel"),names(mtcars[i]),opts)
      )
      }
})

这行得通,但一点也不优雅。 感谢您对我如何改进的意见。

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    我会使用lapply 并将结果包装在tagList 中以创建选择器集合。

    library(shiny)
    library(ggplot2)
    
    shinyApp(
      ui = 
        shinyUI(
          fluidPage(
            selectInput(inputId = "data",
                        label = "Select a dataset",
                        choices = c("mtcars", "iris")),
            uiOutput("select_control")
          )
        ),
    
      server = 
        shinyServer(function(input, output, session){
    
          dataset <- eventReactive(input$data,
                                   get(input$data))
    
    
          output$select_control <- 
            renderUI({
              tagList(
                lapply(names(dataset()),
                       function(x)
                       {
                         selectInput(inputId = sprintf("select_control_%s",
                                                       x),
                                     label = x,
                                     choices = unique(dataset()[[x]]))
                       }
                )
              )
            })
        })
    )
    

    【讨论】:

    • 你有什么理由在你的例子中附加了 ggplot2 吗?
    • 我原本打算在应用程序中包含mpg 数据集。显然我忘记/改变了主意。
    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多