如何通过R Shiny的selectInput更新源脚本变量并动态渲染模型输出
问题根因
你当前的代码没有生效,核心是两个问题:
- 你在应用启动时执行
source("model.R"),脚本里的model_output只会在启动时计算一次,后续即使修改全局变量selected_data,也不会触发model_output重新计算,所以绘图数据永远是初始值 - 你将响应式表达式
selected_data_Change定义在renderPlotly内部属于不必要的写法,且selectInput的返回值本身就是你预设的列名字符串,不需要额外用switch转换
最优实现方案
推荐将模型计算逻辑封装为可传参的函数,调用时传入选择的参数即可实时计算输出结果,修改后的代码如下:
修改后的model.R
# 模型固定数据 yellow_data <- c(10,28,14,40) green_data <- c(20,40,50,90) red_data <- c(50,50,50,80) third_data <- c(30,32,3100,500) data_model <- data.frame(yellow_data, green_data, red_data) # 封装模型计算为可传参函数 get_model_output <- function(selected_data) { union(data_model[[selected_data]] * 200, third_data) }
修改后的app.R
library(shiny) library(plotly) # 启动时加载模型数据和计算函数 source("model.R") ui <- fluidPage( selectInput( inputId = "select_data", label = "SELECT DATA", choices = c( "Yellow" = "yellow_data", "Green" = "green_data", "Red" = "red_data" ) ), plotlyOutput(outputId = "plot_model_output") ) server <- function(input, output, session) { output$plot_model_output <- renderPlotly({ # 传入选择的参数,实时计算模型输出 current_output <- get_model_output(input$select_data) # 绘制图表 plot_ly( x = ~c(1:8), y = ~current_output, name = 'model output', type = 'scatter', mode ='lines' ) }) } shinyApp(ui, server)
如果不想改动原有model.R的结构,也可以在server中每次选择变更后手动重新计算model_output,无需修改model.R代码:
# 仅替换app.R中renderPlotly部分的代码即可 output$plot_model_output <- renderPlotly({ selected_data <- input$select_data # 手动执行model.R中model_output的计算逻辑 model_output <- union(data_model[[selected_data]] * 200, third_data) plot_ly(x = ~c(1:8), y = ~model_output, name = 'model output', type = 'scatter', mode ='lines') })
优先推荐封装函数的方案,后续模型逻辑修改时只需要维护model.R里的函数即可,不用同步修改app.R的代码。
内容的提问来源于stack exchange,提问作者jhonccc
相关产品推荐
相关产品推荐

