简体   繁体   English

R Shiny中的单独计算和绘图

[英]Separate calculation and plotting in R Shiny

I would like to build a shiny app, that runs a simulation and then shows the 3 result plots (I have set them up with tabsetPanel() ). 我想构建一个闪亮的应用程序,运行一个模拟程序,然后显示3个结果图(我已经使用tabsetPanel() )。 The code needs a few seconds to run, so I made a submitButton() . 该代码需要几秒钟才能运行,所以我做了一个submitButton() Now as the code takes longer, I want it to run only once and then display the 3 plots. 现在,随着代码花费更长的时间,我希望它只运行一次,然后显示3个图。 How do I run the code with the input values, extract the 5 result vectors and only then plot them? 如何使用输入值运行代码,提取5个结果向量,然后再绘制它们?

Currently shiny gives an error, because when the code is not within the output$plot <- renderPlot({ ...}) part, it is not reactive. 当前Shiny会给出一个错误,因为当代码不在output$plot <- renderPlot({ ...})部分之内时,它是无响应的。

What I have so far looks like this: 到目前为止,我的情况看起来像这样:

ui <- fluidPage(
titlePanel("My Simulation"),
submitButton(text="RUN SIMULATION")

  mainPanel(
    tabsetPanel(
      tabPanel("Plot 1", plotOutput("p1")), 
      tabPanel("Plot 2", plotOutput("p2")), 
      tabPanel("Plot 3", plotOutput("p3"))
    )
  )
)


server <- function(input, output) {
  v<-reactiveValues(v1=0,v2=0,v3,v4=0,v5=0)
  observeEvent(input,{ myFunction()})

output$p1<-renderPlot{
  plot(v1,v2)
}

output$p2<-renderPlot{
  plot(v1,v3)
}

output$p3<-renderPlot{
  plot(v1,v4)
  lines(v1,v4)
}

shinyApp(ui, server)

Actually it is seperated. 实际上,它是分开的。 To make the plot reactive you have to reference the reactiveValues() as v$v1 , v$v2 ,... It was assigned to v so you would also have to reference it that way. 为了使图具有反应性,您必须将reactiveValues()引用为v$v1v$v2 ,...。它已分配给v因此您也必须以这种方式引用它。 You can actually compare the reactiveValues() to a data.frame() or more like a list that is reactive. 您实际上可以将data.frame() reactiveValues()data.frame()或更像是反应式列表进行比较。 A list v <- list(v1 = 1) you would also call with v$v1 ,... 列表v <- list(v1 = 1)您也可以使用v$v1调用...

Reproducible example: 可重现的示例:

library(shiny)

ui <- fluidPage(
  titlePanel("My Simulation"),
  actionButton(inputId = "simulate", label = "simulate"),

  mainPanel(
    tabsetPanel(
      tabPanel("Plot 1", plotOutput("p1")), 
      tabPanel("Plot 2", plotOutput("p2")), 
      tabPanel("Plot 3", plotOutput("p3"))
    )
  )
)


server <- function(input, output) {

  v <- reactiveValues(v1 = 0, v2 = 0, v3 = 0, v4 = 0, v5 = 0)

  observeEvent(input$simulate,{ 
    v$v1 <- 1
    v$v2 <- 2
    v$v3 <- 3
    v$v4 <- 4
  })

  output$p1<-renderPlot({
    plot(v$v1, v$v2)
  })

  output$p2<-renderPlot({
    plot(v$v1, v$v3)
  })

  output$p3<-renderPlot({
    plot(v$v1, v$v4)
    lines(v$v1, v$v4)
  })
}

shinyApp(ui, server)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM