首页 > 解决方案 > 在反应式中添加 if 语句或过滤 if 语句

问题描述

我正在尝试制作一个闪亮的仪表板/应用程序,用户可以根据各种标准过滤数据。应用过滤器后,用户可以选择他/她希望在条形图中看到的变量以及过滤的数据集。

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

标签: rshinydplyrfilteringshiny-reactivity

解决方案


这就是你需要的——

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

推荐阅读