R shiny selectInput 用于更新源脚本中变量的值,该变量用于计算应用程序绘制的模型输出

R shiny selectInput to update value of a variable in source script, the variable is used to compute the model output plotted by the app

我正在构建一个闪亮的应用程序,用于可视化复杂模型的输出。 该模型位于脚本中,该脚本由闪亮的应用程序提供。 我想用 selectInput 更改模型计算的一个输入并相应地绘制输出模型。

以下是模型源脚本和应用程序的简化版本。

model.R

#data of the model 
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)

#the variable that should be updated by selectInput in the app.R
selected_data <- "yellow_data"

#the model output which should change according to changes in selected_data
model_output <- union(data_model[[selected_data]] * 200, third_data)

我想从应用程序更改变量 selected_data 的值。

app.R

library(shiny)

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({ 
    
    selected_data_Change <- reactive({
      switch(input$select_data,
             "Yellow" = "yellow_data",
             "Green" = "green_data",
             "Red" = "red_data") 
    })
    
    selected_data <<- selected_data_Change()
       
    fig <- plot_ly(x = ~c(1:8), y = ~model_output, name = 'model output', type = 'scatter', mode ='lines')
   fig
  
  })
}
shinyApp(ui, server)

正如您在 app.R 中所见,我尝试使用 selectInput 更新全局变量 selected_data 用于计算 model.R 中的 model_output,来源在 app.R.

我希望 model_output 根据 selectInput.

更新反映

我真的希望你能帮上忙。 谢谢

也许您正在寻找这个

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({ 
    
    #the model output which should change according to changes in selected_data
    model_output <- c(data_model[,as.character(input$select_data)]*200, third_data)
    
    fig <- plot_ly(x = ~c(1:8), y = ~model_output, name = 'model output', type = 'scatter', mode ='lines')
    fig
    
  })
}
shinyApp(ui, server)