按时间段和 R 中的 id 过滤数据帧

Filter dataframe by time period and id in R

问题:

我正在尝试通过依赖于 ID 向量的特定日期时间来过滤我的数据框。

具体来说,对于 df$id == "A" 的观察结果,我想删除 2017-08-05 00:20:002017-08-10 13:55:00 之间的行。但是,对于 df$id == "B" 的观察,我想删除不同时间间隔 2017-08-05 00:30:002017-08-10 13:55:00 之间的行。

示例数据框:

date <- as.POSIXct(c("2017-08-04 16:40:00","2017-08-05 00:20:00","2017-08-10 13:55:00","2017-08-15 08:35:00", "2017-08-04 17:20:00","2017-08-05 00:30:00","2017-08-10 13:55:00","2017-08-15 09:30:00"), format = "%Y-%m-%d %H:%M:%S")
value <- as.numeric(c(1, 2, 3, 4, 1, 2, 3, 4))
id <- as.factor(c("A","A","A","A","B","B","B","B"))
df <- data.frame(date, value, id)

期望输出:

               date value id
2017-08-04 16:40:00     1  A
2017-08-15 08:35:00     4  A
2017-08-04 17:20:00     1  B
2017-08-15 09:30:00     4  B

谢谢!

编辑: 如果您的数据框有第三个类别 (df$id == "C") 您想要完整保留:

df[which(
  (df$id == "A" & (df$date < "2017-08-05 00:20:00" | df$date > "2017-08-10 13:55:00")) |
    (df$id == "B" & (df$date < "2017-08-05 00:30:00" | df$date > "2017-08-10 13:55:00"))
 | df$id == "C"), ]
df[which(
        (df$id == "A" & (df$date < "2017-08-05 00:20:00" | df$date > "2017-08-10 13:55:00")) |
        (df$id == "B" & (df$date < "2017-08-05 00:30:00" | df$date > "2017-08-10 13:55:00"))
      ), ]