Shiny应用:切换Model时自动更新textInput值并生成预测
解决Shiny中车型切换自动更新输入框及预测的问题
以下是基于mtcars数据集的完整可运行Demo,实现车型切换时自动更新参数输入框,并实时生成预测结果:
library(shiny) library(DT) # 提前构建预测模型(以mpg为响应变量,其他参数为自变量) model <- lm(mpg ~ cyl + disp + hp + drat, data = mtcars) ui <- fluidPage( titlePanel("车型参数自动更新与预测"), sidebarLayout( sidebarPanel( # 车型选择下拉框 selectInput("model_select", "选择车型", choices = rownames(mtcars)), # 参数输入框 textInput("cyl", "气缸数(cyl)", value = ""), textInput("disp", "排量(disp)", value = ""), textInput("hp", "马力(hp)", value = ""), textInput("drat", "后轴比(drat)", value = "") ), mainPanel( # 预测结果展示表格 DTOutput("prediction_table") ) ) ) server <- function(input, output, session) { # 监听车型选择变化,更新输入框 observeEvent(input$model_select, { # 获取选中车型的参数 selected_car <- mtcars[input$model_select, ] # 更新各个输入框内容 updateTextInput(session, "cyl", value = as.character(selected_car$cyl)) updateTextInput(session, "disp", value = as.character(selected_car$disp)) updateTextInput(session, "hp", value = as.character(selected_car$hp)) updateTextInput(session, "drat", value = as.character(selected_car$drat)) }) # 生成预测结果 prediction_result <- reactive({ # 检查输入是否有效 if(all(c(input$cyl, input$disp, input$hp, input$drat) != "")){ # 构造预测用的数据框 new_data <- data.frame( cyl = as.numeric(input$cyl), disp = as.numeric(input$disp), hp = as.numeric(input$hp), drat = as.numeric(input$drat) ) # 计算预测值 pred_mpg <- predict(model, newdata = new_data) # 返回结果表格 data.frame( 参数 = c("气缸数", "排量", "马力", "后轴比", "预测油耗(mpg)"), 值 = c(input$cyl, input$disp, input$hp, input$drat, round(pred_mpg, 2)) ) } else { data.frame(参数 = character(), 值 = character()) } }) # 渲染预测结果表格 output$prediction_table <- renderDT({ datatable(prediction_result(), rownames = FALSE, options = list(dom = 't')) }) } shinyApp(ui, server)
关键逻辑说明
- 监听车型切换:通过
observeEvent(input$model_select, {...})捕获车型选择的变化事件,每次切换时从mtcars中提取对应车型的参数。 - 更新输入框:使用
updateTextInput函数,将选中车型的参数值分别更新到对应的输入框中,注意要把数值类型转为字符类型适配textInput的要求。 - 实时预测:用
reactive函数响应输入框的变化,构造预测数据后调用提前训练好的线性模型生成预测结果,最后通过DT表格展示。 - 输入有效性检查:避免输入为空时触发错误,只有所有输入框都有内容时才生成预测结果。
内容的提问来源于stack exchange,提问作者nowyouredoingit
相关产品推荐
相关产品推荐

