【问题标题】:I want to create a dynamic dropdown menu for my Shiny Dashboard using R?我想使用 R 为我的 Shiny Dashboard 创建一个动态下拉菜单?
【发布时间】:2018-04-12 15:37:42
【问题描述】:

我有一个包含多个表的 MySQL 数据库。现在我想在 Shiny 仪表板中创建一个下拉菜单,它会根据表的每一列的唯一值自动添加值。

我当前的代码如下所示

ui <- fluidPage(
  numericInput("nrows", "Enter the number of rows to display:", 5),
  tableOutput("tbl")
)

server <- function(input, output, session) {
    output$tbl <- renderTable({
        conn <- dbConnect(
      drv = RMySQL::MySQL(),
      dbname = "apilogs",
      host = "localhost",
      username = "root",
      password = "root")
        on.exit(dbDisconnect(conn), add = TRUE)
        dbGetQuery(conn, paste0("SELECT * FROM logs where key = 'agc' LIMIT ", input$nrows, ";"))

    })
}

现在,对于我闪亮的仪表板,我想根据日志表列的值创建一个下拉菜单。

  dashboardSidebar(
        selectInput("Filter", "Filter:",
                  choices = c())
  )

现在在choices 中,我想根据表格列动态获取选择。我该怎么做。

【问题讨论】:

  • 使用反应函数将列值放在那里,使用return(x)返回值列表然后创建一个观察函数并使用更新选择输入,将反应()放在选择参数上,你会得到你想要的。

标签: mysql r shiny


【解决方案1】:

我认为,您应该像这样创建唯一的值列表:

unique_values <- sort(unique(table_name$column_name))

然后你可以用它来做选择:

selectInput("filter", "Filter:", choices = unique_values)

对于动态 dropdownMenu,您可以使用此 guide,主要思想是在 UI 部分您只创建以下内容:

ui <- dashboardPage(
  dashboardHeader(title = "Dropdowns 2.0",
    dropdownMenuOutput("dropdownMenuDynamic")
  )
)

你还需要做这样的事情:

size <- length(output$filter)
tasks <- vector("list", size)
for(i in 1:length(tasks)) { 
  tasks[[i]] <- list(
    value = 10,
    color = "yellow",
    text = output$filter[[i]]
  ) 
}

最后一部分是创建 dropdownMenuDynamicon 服务端:

output$dropdownMenuDynamic <- renderMenu({
    items <- lapply(tasks, function(el) {
      taskItem(value = el$value, color = el$color, text = el$text)
    })
    dropdownMenu(
      type = "tasks", badgeStatus = "danger",
      .list = items
    )
  })

【讨论】:

    猜你喜欢
    • 2017-10-04
    • 1970-01-01
    • 2014-07-26
    • 2017-01-06
    • 2012-08-11
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多