首页 > 解决方案 > 如何通过 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)```


标签: rshiny

解决方案


当您在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)

推荐阅读