2016-11-23 50 views
1

我想創建一次數據並在多個圖中重複使用它。下面的示例在每個圖中創建數據,但是如何創建一次(x)並讓每個圖都使用x?在R內創建並重新使用數據Shiny服務器

ui <- shinyUI(
     fluidPage(
       sidebarLayout(
         sidebarPanel(
           numericInput(inputId = "mean", label = "Mean", value = 50) 
         ), 
         mainPanel(
           column(6,plotOutput(outputId = "hist1") 
           ), 
           column(6,plotOutput(outputId = "hist2") 
           ) 
         ) 
       ) 
     ) 
) 


server <- function(input,output){ 

     # I'd like to create the data just once here, and then reuse it in each plot 
     # x <- rnorm(100,input$mean,5) 

     output$hist1 <- renderPlot({ 
       hist(rnorm(100,input$mean,5)) 
       #hist(x) 
     }) 
     output$hist2 <- renderPlot({ 
       hist(rnorm(100,input$mean,5)) 
       #hist(x) 
     }) 
} 

runApp(list(ui = ui, server = server)) 

回答

1

您可以將您的rnorm包裹在一個反應​​式表達式中以創建一個無功導體。然後,在您的端點使用導體(output$)。見http://shiny.rstudio.com/articles/reactivity-overview.html

server <- function(input,output){ 

     # I'd like to create the data just once here, and then reuse it in each plot 
     x <- reactive(rnorm(100, input$mean, 5)) 

     output$hist1 <- renderPlot({ 
       hist(x()) 
     }) 
     output$hist2 <- renderPlot({ 
       hist(x()) 
     }) 
} 
+0

太棒了。我認爲它會是這樣的包裝,但無法解決問題。非常感謝,威煌。 – Murray

1

observe包裝服務器代碼就可以完成這項工作。

server <- function(input,output){ 

    # I'd like to create the data just once here, and then reuse it in each plot 
      observe({ 
      data <- rnorm(100,input$mean,5) 

      output$hist1 <- renderPlot({ 
      hist(data) 
      #hist(rnorm(100,x,5)) 
      }) 

      output$hist2 <- renderPlot({ 
      hist(data) 
      #hist(rnorm(100,x,5)) 
      }) 

     }) 

} 
相關問題