简体   繁体   English

在Shiny应用中使用函数renderUI(selectInput())

[英]using a function to renderUI(selectInput()) in Shiny app

Here's server.r 这是server.r

server <- function(input, output) {
  output$species <- renderUI({
     selectInput("species", 
                 label = "blah", 
                 choices = as.list(unique(iris$Species)))
      })
}

Then over in ui.r 然后在ui.r中

ui <- fluidPage(
   fluidRow(        
       uiOutput("species")
)

This works as expected, a drop down select input appears like this: 这将按预期工作,出现一个下拉选择输入,如下所示: 在此处输入图片说明

Since I have multiple features I need to create a similar filter for in my actual data frame, I tried to do the same with a function: 由于我具有多种功能,因此需要在实际的数据帧中创建一个类似的过滤器,因此我尝试对一个函数执行相同的操作:

In server.r 在server.r中

  outputFilters <- function(id, df) {
    output$id <- renderUI({
     selectInput(id, 
                 label = "blah", 
                 choices = as.list(unique(df$id)))
      })
  }

outputFilters("species", iris)

Then in ui.r same as before uiOutput("species") 然后在ui.r中,与之前的uiOutput("species")

However, now no drop down appears. 但是,现在没有下拉列表出现。 Presumably my function is flawed. 大概我的功能有缺陷。 How can I use a function to generate the drop downs? 如何使用函数生成下拉菜单?

Your problem is that each UI element needs its own id in the output 您的问题是每个UI元素在output需要有自己的id

 outputFilters <- function(id, df) {
    output[[id]] <- renderUI({
     selectInput(id, 
                 label = "blah", 
                 choices = as.list(unique(df[[id]])))
      })
  }

now as long as id is a string in the function input it should generate the output element and you can refer with said id 现在,只要id是函数输入中的字符串,它就应该生成输出元素,您可以使用该id进行引用

You could then even use lapply to iterate over numerous, kind of how florian suggests. 然后,您甚至可以使用lapply遍历大量类似lapply建议。

Note that you could also do without a separate function in this case, by wrapping the desired ui component in lapply , or putting the lapply within the uiOutput to create all inputs at once, below is an example for the both two cases. 请注意,在这种情况下,也可以不使用单独的功能,方法是将所需的ui组件包装在lapply ,或者将lapply放在uiOutput以一次创建所有输入,以下是这两种情况的示例。 Hope this helps! 希望这可以帮助!

ibrary(shiny)

ui <- fluidPage(
  uiOutput('Species'),
  uiOutput('Sepal.Length'),
  h2('All inputs: '),
  uiOutput('my_inputs')
)


server <- function(input, output) {

  # Use lapply to create multiple uiOutputs.
  lapply(colnames(iris), function(x){
    output[[x]] <- renderUI({
      selectInput(paste0('input_',x), 
                  label = x, 
                  choices = as.list(unique(iris[['x']])))
    })
  })

  # Create all dropdown's at once.
  output$my_inputs <- renderUI({
    lapply(colnames(iris), function(x){
      selectInput(paste0('input_',x), 
                  label = x, 
                  choices = as.list(unique(iris)))
    })
  })

}

shinyApp(ui, server)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM