【问题标题】:dplyr filter variable set to filter nothing [r]dplyr 过滤器变量设置为不过滤 [r]
【发布时间】:2019-04-04 18:47:20
【问题描述】:

是否有一个值会使 dplyr 过滤器不过滤任何东西?我正在使用一个变量来根据 Shiny 中的下拉菜单进行过滤。

我知道像this 这样的 if 语句有答案。但是,我很好奇是否有办法通过将过滤器值设置为等于“不过滤任何东西”的值。

这是我正在尝试的一个可重现的示例。

library(dplyr)

my_df <- structure(
  list(
    `Month Nm` = c("October", "August", "August",
                   "March", "January", "July"),
    Cycle = c(
      ">= 2nd Cycle Action",
      ">= 2nd Cycle Action",
      ">= 2nd Cycle Action",
      ">= 2nd Cycle Action",
      "ACK or RTA",
      ">= 2nd Cycle Action"
    )
  ),
  row.names = c(NA,-6L),
  class = c("tbl_df",
            "tbl", "data.frame")
)

filter_var <- October"

my_df %>% filter(`Month Nm` == filter_var) %>% View()

# How can I set the variable (filter_var) that will make the filter not filter anything?
filter_var <- "" # What can I set this to? 

my_df %>% filter(`Month Nm` == filter_var) %>% View() # I want the output to be everything

我尝试将值设置为 NULL 和 TRUE 和 FALSE 只是为了好玩,但没有运气。

我想一种方法是在感兴趣的列中找到所有不同的值并基于所有这些方式进行过滤?还有更简洁的方法吗?

【问题讨论】:

  • 这只是我整体代码的一个例子。我让用户从 Shiny 下拉菜单中选择特定名称,然后该名称成为我要过滤的变量。然后,在我的 Shiny 应用程序的其他地方,输出会根据过滤器进行更新。问题是,如果用户没有选择过滤器,或者完全删除下拉值,我的代码中仍然有 filter = filter_var。有没有办法以实际上不过滤任何东西的方式设置 filter_var ?我能想到的唯一方法是找到所有不同的值并设置 filter_var = all_distinct。
  • 我试图避免使用“if”选项,因为代码实际上比我的示例复杂得多,而且我的 Shiny app.R 文件中嵌入了很多代码。实际上,我只是发现我可以捕获 Shiny Drop Down 输入并根据该输入在另一个脚本中调用函数。我不确定如何从闪亮的输出块中调用函数。事实证明你可以做到。我想我不再需要答案了。但是,如果没有“if”语句,知道这是否可行仍然会很好。

标签: r dataframe filter shiny dplyr


【解决方案1】:

您可以简单地创建一个虚拟测试值并在您的过滤条件中使用它,如下所示 -

dummy <- "all"

filter_var <- "all"

my_df %>%
  filter(`Month Nm` == filter_var | filter_var == dummy)

# A tibble: 6 x 2
  `Month Nm` Cycle              
  <chr>      <chr>              
1 October    >= 2nd Cycle Action
2 August     >= 2nd Cycle Action
3 August     >= 2nd Cycle Action
4 March      >= 2nd Cycle Action
5 January    ACK or RTA         
6 July       >= 2nd Cycle Action

filter_var <- "August"

my_df %>%
  filter(`Month Nm` == filter_var | filter_var == dummy)

# A tibble: 2 x 2
  `Month Nm` Cycle              
  <chr>      <chr>              
1 August     >= 2nd Cycle Action
2 August     >= 2nd Cycle Action

dummy 应该是实际过滤器变量中不存在的值。

【讨论】:

    【解决方案2】:

    如果您可以提供帮助(在这种情况下您可以提供帮助),我建议不要更改您的数据框以包含实现细节。

    您可以直接在 filter 语句中使用 or 语句。只需在名为"All Months" 的下拉菜单中添加一个选项,然后更改您的filter 语句:

    my_df %>% filter(`Month Nm` == filter_var | filter_var == "All Months") %>% View()`
    

    【讨论】:

      猜你喜欢
      • 2013-01-19
      • 2023-03-12
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多