我无法使用闪亮的摘要(均值函数)来绘制条形图

时间:2019-09-13 16:46:06

标签: r shiny

我试图计算每个物种内踏板长度(或宽度)的平均值,然后使用shinny应用程序将其绘制在条形图中。但是总结中的均值函数不断给我带来问题。

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

定义绘制直方图所需的服务器逻辑

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

        })

}

运行应用程序

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

在这里,它是一个字符串元素,因此请转换为sym bol并求值(!!

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

        })

}

-测试

shinyApp(ui = ui, server = server)

-输出

enter image description here