在反应式中添加 if 语句或过滤 if 语句

Add if statement or filter if statement in a reactive

我正在尝试制作一个闪亮的 dashboard/app,用户可以根据各种条件过滤数据。应用过滤器后,用户可以选择 he/she 想要在条形图中查看的变量以及过滤后的数据集。

对于示例代码,我希望用户能够按位置进行过滤。级别为亚特兰大、芝加哥和西雅图。但是,我还希望用户能够在默认情况下一次按所有城市进行过滤。 All 不是数据集中的一个选项,所以我想添加一个 "All" 选项。因此,我希望人们 filter_if 输入 $location_type != "All",但我无法让它工作。下面是我的代码,只有过滤器——如果你能修改它使 filter_if 工作,我将不胜感激!

library(tools)
library(dplyr)
library(shiny)
library(ggplot2)
ui <- fluidPage(
  sidebarLayout(
  sidebarPanel(

  selectInput(inputId = "x",
              label = "Predictor:",
              choices = c("ID", "location", "title", "job_sat", "motivation", "commitment", "review"),
              selected = "ID"),
  selectInput(inputId = "y",
              label = "Outcome:",
              choices = c("ID", "sales", "location", "title", "job_sat", "motivation", "commitment", "review"),
              selected = "sales"),
  textInput(inputId = "plot_title",
            label = "Plot Title:",
            placeholder = "Enter text for this plot's title"),
  selectInput(inputId = "location_type",
              label = "Location:",
              choices = c("All", levels(fakeshinydata$location)),
              selected = "All",
              multiple = TRUE)
),
mainPanel(
  plotOutput(outputId = "scatterplot")
)
)
)

server <- function(input, output) {


  fake_subset <- reactive({
    req(input$location_type)
    dplyr::filter(fakeshinydata, location %in% input$location_type)
   })

   pretty_plot_title <- reactive({toTitleCase(input$plot_title)})

  output$scatterplot <- renderPlot({
ggplot(data = fake_subset(),
       aes_string(x = input$x, y = input$y)) +
  geom_point() +
  labs(title = pretty_plot_title())
    })
}

 shinyApp(ui = ui, server = server)

这是您需要的 -

fake_subset <- reactive({
  req(input$location_type)
  filter(fakeshinydata, (location %in% input$location_type) | (input$location_type == "All"))
})