Bruno Guarita
Bruno Guarita

Reputation: 817

Create shiny dashboard sidebar menu from dataframe

I am trying to create menu items under the dashboard Sidebar automatically from a table without success. I am using the code below.

library(shiny)
library(shinydashboard)

header = dashboardHeader(title = "title")
sidebar = dashboardSidebar(sidebarMenuOutput("sidebarMenu"))
body = dashboardBody()

ui = dashboardPage(header, sidebar, body)


labels = data.frame(id = c(1,2,3),
                    name = c("lab1", "lab2", "lab3"))

server = function(input, output) { 

  output$sidebarMenu <- renderMenu({
    sidebarMenu(id="tabs",
                for (i in labels) {
                  menuItem(labels$name[i], tabName = labels$id[i])
                  })


  })
}


shinyApp(ui, server)

data.frame labels contains the labels and id I need to use in the menu. I am running a for loop. How should I do it?

Upvotes: 2

Views: 624

Answers (1)

DSGym
DSGym

Reputation: 2867

for (i in labels)

This loop does not work since you will always get the dataframe, not not a row of the dataframe. Anyhow, I did not get it to work with the loop, i normally use a combination of lapply to store all items in a list and use do.call to visualize it with the renderUI function.

library(shiny)
library(shinydashboard)

labels = data.frame(id = c(1,2,3),
                    name = c("lab1", "lab2", "lab3"))

header = dashboardHeader(title = "title")
sidebar = dashboardSidebar(sidebarMenu(id="mytabs",
                                    uiOutput("sidebar_menu_UI")))
body = dashboardBody()

ui = dashboardPage(header, sidebar, body)


server = function(input, output) { 

    output$sidebar_menu_UI <- renderUI({

        myTabs = lapply(1:nrow(labels) , function(i) {

            menuItem(labels$name[i], tabName = labels$id[i])  
        })

        print(myTabs)

        do.call(sidebarMenu, myTabs)
    })
}


shinyApp(ui, server)

Upvotes: 3

Related Questions