R shiny ggplot facet_wrap 取决于 select 输入

R shiny ggplot facet_wrap that depends on select input

我正在尝试制作一个 R shiny 应用程序,它允许您 select 一个群体(性别、年龄、种族等),然后在 facet_wrap 对于该组中的每个级别。例如,如果将性别 select 编辑为组,则直方图将具有男性和女性的分面。在我下面的代码中,它没有产生任何方面。

library(shiny)
library(ggplot2)
# Define UI for miles per gallon app ----
ui <- fluidPage(

  # Application title
  titlePanel("Group fairness analysis"),

  # Sidebar 
  sidebarLayout(
    sidebarPanel(
      selectInput("group", "Group:", 
                  c("Age" = "age",
                    "Gender" = "gender",
                    "Region" = "region",
                    "Ethnicity"="ethnicity"))
      ),

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

# Define server logic----
server <- function(input, output) {

  output$distPlot <- renderPlot({   
  gg <- ggplot(df, aes(x=score))+
      geom_histogram(breaks=seq(0,100,10))+
      facet_wrap(~input$group)
      gg

  })

}

shinyApp(ui, server)

它不起作用,因为 input$group 是字符类型,而 facet_wrap 需要带引号的变量。

直接用get引用即可解决:

gg <- ggplot(df, aes(x=score))+
      geom_histogram(breaks=seq(0,100,10))+
      facet_wrap(~get(input$group))

希望对您有所帮助!