用于多个 renderPlot 函数的过滤数据框

Filter data frame for use in multiple renderPlot functions

我有一个闪亮的应用程序,它使用反应式表达式来响应用户从下拉列表中选择一个值。

然后将选择的值用作数据框的过滤条件。

如果我想创建 相同 过滤数据框的两个不同图,我是否必须调用反应表达式两次,每个 renderPlot 函数一次(如下面的示例代码所示),或者有没有办法存储过滤数据框的结果以供不同的 renderPlot 调用使用?

server.R

library(shiny)
library(dplyr)
library(ggplot2)

shinyServer(function(input, output) {

    ## create dummy data
    set.seed(1)
    location <- c("locA", "locB", "locC")
    location <- sample(location, 20, replace=TRUE)
    service <- c("serviceA", "serviceB")
    service <- sample(service, 20, replace=TRUE)
    person <- c("A", "B")
    person <- sample(person, 20, replace=TRUE)
    value <- runif(20, 0, 5)

    df <- data.frame(location, service, person, value)

    ## reactive to user input
    select <- reactive({
        input$select
    })

    ## plot 1
    output$plot1 <- renderPlot({
        ## filter data frame for use in first plot
        df <- df %>%
            filter(person==select())   ## select() - calls reactive expression

        ggplot(data=df, aes(x=location, y=value, fill=person)) +
            geom_bar(stat="identity")
    })    
    ## plot 2
    output$plot2 <- renderPlot({
        ## filter data frame for use in second plot 
        ## this is the same data as in plot1
        df <- df %>%
            filter(person==select())  ## select() - calls reactive expression

        ggplot(data=df, aes(x=location, y=value, fill=person)) +
        geom_bar(stat="identity") +
            facet_wrap(~service)
    })  
})

ui.R

library(shiny)

shinyUI(navbarPage("Test",
                   tabPanel("panel",
                            sidebarLayout(
                                sidebarPanel(
                                    selectInput("select", label="select", choices=c("A", "B"))
                                ),
                                mainPanel(
                                    plotOutput("plot1"),
                                    hr(),
                                    plotOutput("plot2")
                                    )
                                )
                            )
                   )
        )

这只是一个基本示例;我的实际应用程序将在许多不同的图中使用相同的计算和过滤数据框,所以我希望它不必重新运行每个图的过滤条件。

因此信息流为:

Select_Input > filter_data > (plot1, plot2, plot3, ... plotn)

您可以将数据框的过滤包装在 reactive 表达式中,并在绘图的每个数据参数中调用 filter_df()

  filter_df <- reactive({
    df %>%
      filter(person==select())
  })