gpt4 book ai didi

r - 我不能在 shiny 中使用 summarize (mean function) 来绘制条形图

转载 作者:行者123 更新时间:2023-12-04 14:18:19 26 4
gpt4 key购买 nike

我尝试计算每个物种的平均踏板长度(或宽度),然后使用 Shiny 的应用程序将其绘制在条形图中。但是 summarize 中的 mean 函数一直给我带来问题。

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)

最佳答案

在这里,它是一个字符串元素,因此转换为symbol 并计算(!!)

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

关于r - 我不能在 shiny 中使用 summarize (mean function) 来绘制条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57927497/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com