Shiny吗啡预测应用报错:缺少sidebar参数无默认值,寻求修复方案
问题分析与解决方案
错误原因
dashboardPage是shinydashboard的核心布局函数,必须传入header、sidebar、body三个必填参数。你的原代码仅传入了dashboardHeader,dashboardSidebar和dashboardBody被写成了独立语句,未作为参数传入dashboardPage,导致抛出"缺少sidebar参数"的错误。此外,侧边栏和标签页的嵌套结构也存在错误:sidebarMenu需放在dashboardSidebar内部,tabItem必须嵌套在tabItems中再放入dashboardBody。
修正后的UI代码
# 加载依赖包 library(shiny) library(shinydashboard) library(ggplot2) library(dplyr) library(randomForest) library(Metrics) # 构建UI ui <- dashboardPage( # 页面头部 dashboardHeader(title = '吗啡消耗量预测工具', titleWidth = 290), # 侧边栏 dashboardSidebar( sidebarMenu( id = "menu", menuItem("变量可视化", tabName = "plots", icon = icon('poll')), menuItem("数据看板", tabName = "dash", icon = icon('tachometer-alt')), menuItem("消耗量预测", tabName = "pred", icon = icon('search')) ) ), # 主内容区 dashboardBody( tags$head(tags$style(HTML('.main-header .logo {font-weight: bold;}'))), tabItems( # 可视化标签页 tabItem('plots', box(status = 'primary', title = '直方图筛选变量', selectInput('num', "数值型变量:", c("Age", "BMI", "IV_Fluids", "Operative_times", "Blood_loss", "Time_to_Aldrete_9", "morphine_consumption_24h1", "VAS_basalR", "VAS_basalM", "VAS_2hrR", "VAS_2hrM", "VAS_4hrM", "VAS-4hrR", "VAS_8hrR", "VAS_8hrM", "VAS_12hrR", "VAS_12hrM", "VAS_16hrR", "VAS_16hrM", "VAS_24hrR", "VAS_24hrM", "QOR_psychological_support", "QOR_emotional_state", "QOR_Physical_comfort", "QOR_physical_independence", "QOR_Pain", "Total")), footer = '数值变量分布直方图'), box(status = 'primary', title = '频数图筛选变量', selectInput('cat', '分类型变量:', c("ASA", "Postoperative_vomiting", "Sedation_0to8h", "Sedation_9to16h", "Sedation_17to24h")), footer = '分类变量频数统计图'), box(plotOutput('histPlot')), box(plotOutput('freqPlot')) ), # 预测标签页 tabItem('pred', box(title = '分类变量输入', status = 'primary', width = 12, splitLayout( tags$head(tags$style(HTML(".shiny-split-layout > div {overflow: visible;}"))), cellWidths = c('19%', '4%', '19%', '4%', '19%', '4%', '19%', '4%', '8%'), selectInput( 'p_group', '分组', c("0", "30", "60", "90")), div(), selectInput('p_ASA', 'ASA分级', c('1', '2', '3')), div(), selectInput( 'p_Sedation_17to24h', '17-24h镇静评分', c('1', '2', '3', '4')), div(), radioButtons( 'p_Postoperative_vomiting', '术后呕吐', c('是', '否')) ) ), box(title = '数值变量输入', status = 'primary', width = 12, splitLayout(cellWidths = c('22%', '4%','21%', '4%', '21%', '4%', '21%'), sliderInput( 'p_Age', '年龄(岁)', min = 0, max = 100, value = 50), div(), numericInput( 'p_BMI', 'BMI指数', 22), div(), numericInput( 'p_VAS_24hrM', '24h活动时VAS评分', 3), div(), numericInput( 'p_QOR_psychological_support', 'QOR-心理支持评分', 10), div(), numericInput( 'p_QOR_Pain', 'QOR-疼痛评分', 10), numericInput( 'p_QOR_Physical_comfort', 'QOR-躯体舒适度评分', 10) ) ), box(title = '预测结果', status = 'success', solidHeader = TRUE, width = 4, height = 260, div(h5('吗啡24小时消耗量(mg):')), verbatimTextOutput("value", placeholder = TRUE), div(h5('消耗量预测范围:')), verbatimTextOutput("range", placeholder = TRUE), actionButton('cal','计算', icon = icon('calculator')) ), box(title = '模型说明', status = 'success', width = 8, height = 260, helpText('本模型基于年龄、BMI、24h活动时VAS评分、术后恢复质量(QOR)等变量,预测患者24小时吗啡消耗量。'), helpText('训练数据集来自UCI机器学习仓库,研究主题为"术前度洛西汀对改良根治术患者的短期疗效",包含17379条观测记录。'), helpText(sprintf('模型采用随机森林算法,训练集上的平均绝对误差(MAE)为%s mg,均方根误差(RMSE)为%s mg。', round(mae_rf, digits = 0), round(rmse_rf, digits = 0))) ) ) ) ) )
修正后的Server代码
server <- shinyServer(function(input, output) { # 变量可视化模块 output$histPlot <- renderPlot({ # 补充你的直方图绘制逻辑,示例: # data %>% ggplot(aes_string(x = input$num)) + geom_histogram(bins = 15, fill = "#2c3e50") + theme_minimal() }) output$freqPlot <- renderPlot({ # 补充你的频数图绘制逻辑,示例: # data %>% ggplot(aes_string(x = input$cat)) + geom_bar(fill = "#3498db") + theme_minimal() }) # 数据看板模块(按需补充) output$linePlot <- renderPlot({}) output$barPlot <- renderPlot({}) # 预测模块 a <- reactiveValues(result = NULL) observeEvent(input$cal, { # 注意:需提前加载训练好的模型model_rf、测试集test_set、误差指标mae_rf # 移除原代码中未定义的p_mnth参数 values = data.frame( Group = input$p_group, ASA = input$p_ASA, Sedation_17to24hr = input$p_Sedation_17to24h, PONV = input$p_Postoperative_vomiting, Age = input$p_Age, BMI = input$p_BMI, VAS_24hrM = input$p_VAS_24hrM, QOR_psychological_support = input$p_QOR_psychological_support, QOR_Pain = input$p_QOR_Pain, QOR_Physical_comfort = input$p_QOR_Physical_comfort ) # 确保输入变量名与模型训练时的特征名完全一致 a$result <- round(predict(model_rf, newdata = values), digits = 0) }) output$value <- renderText({ if(is.null(a$result)) "请点击计算按钮" else paste(a$result) }) output$range <- renderText({ input$cal isolate({ if(is.null(a$result)) "" else sprintf('%s - %s mg', round(a$result - mae_rf, digits = 0), round(a$result + mae_rf, digits = 0)) }) }) }) shinyApp(ui, server)
其他注意事项
- 前置依赖准备:需提前加载训练好的随机森林模型
model_rf、测试集test_set、误差指标mae_rf和rmse_rf,确保这些对象在运行Shiny应用前已定义。 - 变量名一致性:输入控件的命名需与模型训练时的特征名完全匹配,否则预测会失败。
- 可视化逻辑补充:需在
renderPlot中补充具体的绘图代码,基于你使用的数据集完成变量可视化功能。
内容的提问来源于stack exchange,提问作者Aly
相关产品推荐
相关产品推荐

