2016-11-23 9 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

驚くばかりです。私はこのようなラッパーのようなものだと思っていたが、うまくいかなかった。多くのおかげで、Weihuang。 – 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)) 
      }) 

     }) 

} 
関連する問題