Q:

I can't use summarize (mean function) in shiny to plot bar graph

I tried to calculate the average of pedal length (or width) within in each species and then plot it in bar graph using the shinny app. But the mean function in summarize keeps giving me issues.  
library(datasets)
library(shiny)
library(dplyr)
library(ggplot2)
data("iris")

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Analyze Iris table"),

    # Sidebar with a dropdown menu selection input for key meausre compoenent
    sidebarLayout(
        sidebarPanel(
            selectInput("yInput", "Measuring element: ", 
                            colnames(iris), selected = colnames(iris)[2]), 
            selectInput('xInput', 'Grouper: ', 
                            colnames(iris), selected = colnames(iris)[5])
        ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("barPlot")
        )
    )
)

Define server logic required to draw a histogram
server <- function(input, output) {

    by_xInput <- reactive({

        iris %>% 
        group_by(input$xInput) %>% 
        summarize(n = length(input$xInput), mean_y = mean(input$yInput))

        })

    output$barPlot <- renderPlot({
        # generate bins based on input$bins from ui.R
        ggplot(data = by_xInput(), aes(x = input$xInput, y = mean_y)) + 
            geom_bar(stat = 'identity')

        })

}

Run the application
shinyApp(ui = ui, server = server)

A:

Here, it is a string element, so convert to symbol and evaluate (!!)
library(dplyr)
library(shiny)
library(ggplot2)
server <- function(input, output) {

    by_xInput <- reactive({

      iris %>% 
        group_by_at(input$xInput) %>% 
        # n() can replace the length
        # convert string to symbol and evaluate (!!)
        summarize(n = n(), mean_y = mean(!! rlang::sym(input$yInput)))

        })

    output$barPlot <- renderPlot({

        # as the input is a string, use `aes_string`
        ggplot(data = by_xInput(), aes_string(x = input$xInput, y = "mean_y")) + 
            geom_bar(stat = 'identity')

        })

}

-testing
shinyApp(ui = ui, server = server)

-output

