r - 如何通过 2 个步骤在闪亮中使用用户选择的变量
问题描述
我在这里包括可重现的例子。我希望用户选择一个变量,该变量将作为参数传递给 group_by 函数。然后我想绘制聚合数据。虽然我能够在稍后计算聚合时找到如何引用用户输入,但当我想在图表中引用相同的变量时,我不知道该怎么做。在我的示例中,我需要为占位符 xxxxxxxxxxx 找到正确的答案,或者可能找到不同的解决方案
library(shiny)
ui <- fluidPage(
selectInput("first","Select variable",c("cyl","gear")),
plotOutput("distPlot")
)
server <- function(input, output) {
data<-reactive({
mtcars%>%group_by(!!input$first)%>%summarise(average=mean())
})
output$distPlot <- renderPlot({
ggplot(data(),aes(XXXXXXXXXXXXXX,average))+
geom_bar(stat = 'identity')
})
}
shinyApp(ui, server)```
解决方案
当您在group_by
函数和 ggplotaes
函数中引用 input$first 时,您必须编写!!sym(input$first)
.
library(shiny)
library(ggplot2)
ui <- fluidPage(
selectInput("first","Select variable",c("cyl","gear")),
plotOutput("distPlot"),
)
server <- function(input, output) {
data<-reactive({
mtcars%>%
group_by(!!sym(input$first)) %>%
summarise(average=mean(mpg))
})
output$distPlot <- renderPlot({
ggplot(data(),aes(x=!!sym(input$first),y=average)) +
geom_bar(stat = 'identity')
})
}
shinyApp(ui, server)
要了解为什么需要sym
考虑以下因素:
library(shiny)
library(ggplot2)
ui <- fluidPage(
selectInput("first","Select variable",c("cyl","gear")),
tableOutput("wrong"),
tableOutput("correct")
)
server <- function(input, output) {
output$wrong <- renderTable({
mtcars%>%
group_by(!!input$first) %>%
summarise(average=mean(mpg))
})
output$correct <- renderTable({
mtcars%>%
group_by(!!sym(input$first)) %>%
summarise(average=mean(mpg))
})
}
shinyApp(ui, server)
推荐阅读
- javascript - 在画布上绘制可拖动对象的重构代码
- processing - 处理:代码停止工作而不对其进行任何更改
- php - Laravel 5:如何重置内置油门/速率限制器?
- c# - Windows 2008 服务器上的 WCF 服务错误
- php - PHP:如何防止用户在登录后单击返回按钮时进入登录页面?
- c++ - 使用 isdigit 和 isalpha 设置 char 数组彼此相等
- android - 检测 Apk 中的代码篡改
- javascript - 在图像悬停Jquery上显示div
- cookies - 为什么即使在完全清理了我的浏览器后,Google cookie 仍会发送到第三方网站?
- c - 如何防止 clang/llvm 将局部变量编译为全局变量?