我正在制作一个ShinyDashboard程序,在寻找在MenuItems中进行循环的方法时遇到了一些麻烦。具体来说,我正在寻找可以代替以下几行的内容:
menuItem(
"Section1",
tabName = "Section1",
startExpanded = T,
menuSubItem("Sub Menu 1", tabName = "tab1"),
menuSubItem("Sub Menu 2", tabName = "tab2")
),
menuItem(
"Section2",
tabName = "Section2",
startExpanded = T,
menuSubItem("Sub Menu 1", tabName = "tab1"),
menuSubItem("Sub Menu 2", tabName = "tab2")
)
这是我尝试过的:
lapply(1:2, function(i){
do.call(menuItem, c(text = paste0("Section",i), tabName =paste0("Section",i), startExpanded = T,
lapply(1:2, function(j) {
menuSubItem(text = paste0("sub menu ", j), tabName=paste0("tab",j))
}
)))
})
它抛出以下错误:
错误:$运算符对于原子向量无效
我读了一篇与dashboardBody-> tabItems
类似的文章。How to make a function in a for loop or lapply loop in a tabItem dashboard shiny
非常感谢您的帮助。
答案 0 :(得分:0)
我不确定是否要找到它,但是下面的代码动态创建了这两个菜单项及其子项。
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title = "My Page"),
dashboardSidebar(sidebarMenuOutput("sidebar_menu")),
dashboardBody(
NULL
)
)
server <- shinyServer(function(input, output, session) {
output$sidebar_menu <- renderMenu({
sidebarMenu(id = "tab",
menuItem("Section1", tabName="Section2", startExpanded = T,
lapply(1:2, function(i) {
menuSubItem(paste0("Sub Menu ",i), tabName = paste0("tab",i))
})
),
menuItem("Section2", tabName="Section2", startExpanded = T,
lapply(1:2, function(i) {
menuSubItem(paste0("Sub Menu ",i), tabName = paste0("tab",i))
})
)
)
})
})
runApp(list(ui= ui, server = server))
答案 1 :(得分:0)
找到了解决方案
output$menu <- renderMenu(
{
sidebarMenu(id = "sbm",
lapply(1:10, function(i){
do.call(menuItem, c(text = paste0("Section",i), tabName = paste0("Section",i), startExpanded = T,
lapply(1:2, function(j) {
menuSubItem(text = paste0("sub menu ", j), tabName=paste0("tab",j))
}
)))
}
))
})