簡體   English   中英

dplyr過濾器變量設置為不過濾任何內容[r]

[英]dplyr filter variable set to filter nothing [r]

是否有一個值會使dplyr過濾器不過濾任何內容? 我正在使用變量基於Shiny中的下拉菜單進行過濾。

我知道有有如果答案之類的語句這樣 但是,我很好奇是否有一種方法可以通過將過濾器值設置為等於“不過濾任何東西”的值來實現。

這是我正在嘗試的可復制示例。

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只是為了好玩,但沒有運氣。

我想做到這一點的一種方法是在感興趣的列中找到所有不同的值,然后基於所有方式進行過濾? 還有更簡潔的方法嗎?

您可以簡單地創建一個虛擬測試值,並將其用於您的過濾條件,如下所示-

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應該是您的實際過濾器變量中尚不存在的值。

如果可以幫助,我建議不要更改數據框以包括實現細節(在這種情況下可以幫助實現)。

您可以直接在filter語句中使用or語句。 只需在下拉菜單中添加一個名為"All Months" ,然后更改您的filter語句即可:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM