在R服务器中创建和重用数据

在R服务器中创建和重用数据,r,shiny,R,Shiny,我想创建一次数据并在多个绘图中重用它。下面的示例在每个绘图中创建数据,但是如何创建一次(x)并使每个绘图使用x ui <- shinyUI( fluidPage( sidebarLayout( sidebarPanel( numericInput(inputId = "mean", label = "Mean", value = 5

我想创建一次数据并在多个绘图中重用它。下面的示例在每个绘图中创建数据,但是如何创建一次(x)并使每个绘图使用x

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))

ui用
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))
            })

         })

}

server您可以将
rnorm
包装在反应式表达式中,以创建反应式导体。然后,在端点中使用导体(
output$
)。看


服务器太棒了。我以为是像这样的包装纸,但没办法。谢谢你,卫煌。
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())
        })
}