【问题标题】:Using filter_if to filter based on a criteria使用 filter_if 根据条件进行过滤
【发布时间】:2020-05-25 00:16:30
【问题描述】:

我正在尝试根据“类型”列过滤数据框,如果“类型”匹配,则在“日期”上应用过滤条件。这是一个例子:

df <- tibble(type = c("A","A","A","A","B","B","B","B","C","C","C","C"),
           Date = ymd(c(20190101,20190105,20190110,20191231,20190530,20190630,20190730,20180630,20190730,20190112,20191230,20181215)))

    A_date <- c(ymd(2019-01-05),ymd(2019-12-31))
    B_date <- c(ymd(2019-05-30),ymd(2019-07-30))
    C_date <- c(ymd(2019-01-01),ymd(2019-12-15))

df
# A tibble: 12 x 2
   type  Date      
   <chr> <date>    
 1 A     2019-01-01
 2 A     2019-01-05
 3 A     2019-01-10
 4 A     2019-12-31
 5 B     2019-05-30
 6 B     2019-06-30
 7 B     2019-07-30
 8 B     2018-06-30
 9 C     2019-07-30
10 C     2019-01-12
11 C     2019-12-30
12 C     2018-12-15

我想应用一个过滤器,如果类型为“A”,则过滤所有类型为“A”且日期在 A_date 之间的行,并对“B”和“C”执行相同的操作。这样生成的数据框将是:

# A tibble: 8 x 2
   type  Date      
   <chr> <date>    
 1 A     2019-01-05
 2 A     2019-01-10
 3 A     2019-12-31
 4 B     2019-05-30
 5 B     2019-06-30
 6 B     2019-07-30
 7 C     2019-07-30
 8 C     2019-01-12

是否可以使用 tidyverse 的“filter_if”来做到这一点?如果没有,还有其他解决方案吗?

【问题讨论】:

  • 如果您只有几种类型,您可以使用普通过滤器来完成。您只想在过滤器中做一些逻辑语句,例如(type == "A" &amp; between(Date, start, end)) | (type == "B" &amp; between(Date, start, end) | ...
  • 用更多“类型”键入所有这些过滤器可能太麻烦了......不过谢谢:)

标签: r date if-statement filter


【解决方案1】:

如果您输入每个数据帧的开始日期和结束日期,您可以通过加入和过滤轻松做到这一点。

library(dplyr)
library(lubridate)

ref <- data.frame(type= c('A', 'B', 'C'), start = ymd(c('2019-01-05', '2019-05-30', 
     '2019-01-01')), end = ymd(c('2019-12-31', '2019-07-30', '2019-12-15')))


df %>%
  left_join(ref, by  ='type') %>%
  filter(Date >= start & Date <= end) %>%
  select(type, Date)

在基础 R 中类似:

subset(merge(df, ref), Date >= start & Date <= end)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 2021-01-04
    相关资源
    最近更新 更多