Filter data frame for use in multiple renderPlot functions

I have a brilliant application that uses a reactive expression to respond to a user to select a value from a drop-down list.

The selected value is then used as the filter condition in the data frame.

If I want to create two different graphs of the same filtered data frame, do I need to call the reactive expression twice for each function renderPlot(as in the example below), or is there a way to save the results of the filtered data frame for use by different calls 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)
+3
1

reactive filter_df() :

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

Source: https://habr.com/ru/post/1620463/


All Articles