通过滚动日期或连续过滤日期来过滤数据

问题描述 投票:-1回答:2

我正在根据日期过滤数据框...现在如何获取上个月相同日期的数据?

df<-data.frame(
  Date=sample(seq(as.Date('2018-10-25'), as.Date('2018-11-20'), by = "day"), 100,replace = T),
  category1=sample(letters[1:6],100,replace = T),
  count=sample(1:1000,100,replace = T)
)

df%>%filter(Date < Sys.Date()-1 & Date >= Sys.Date()-8) %>%group_by(Date,category1)%>%summarise(Total=sum(count))


Output:
# A tibble: 19 x 3
# Groups:   Date [?]
   Date       category1 Total
   <date>     <fct>     <int>
 1 2018-11-13 a           231
 2 2018-11-14 e           763
 3 2018-11-14 f            50
 4 2018-11-15 a           643
 5 2018-11-15 e           745
 6 2018-11-15 f           931
 7 2018-11-16 b           712
 8 2018-11-16 e           416
 9 2018-11-16 f           914
10 2018-11-17 a           270
11 2018-11-17 b           837
12 2018-11-17 d          1539
13 2018-11-17 e           251
14 2018-11-18 a          1181
15 2018-11-18 f           966
16 2018-11-19 a           673
17 2018-11-19 b           960
18 2018-11-19 d           768
19 2018-11-19 e           932

以上输出是11月13日到11月19日那么如何获取10月份相同日期的数据?

r dplyr lubridate
2个回答
2
投票

如果我理解正确,您可以从当前过滤条件中减去1个月。

library(dplyr)
library(lubridate)

df %>%
  filter(Date < (Sys.Date() - 1 - months(1)) & 
         Date >= (Sys.Date() - 8 - months(1))) %>%
  group_by(Date,category1) %>%
  summarise(Total = sum(count))

这将为您提供10月份相同日期的行。


0
投票

使用“月”时要小心,因为它会减去日期中月份的数量。如果新值在该月没有那么多天,它将导致问题;例如,从2018-03-31减去1

> x <- ymd(20180331)
> x
[1] "2018-03-31"
> x - months(1)  # the 31th of February does not exist
[1] NA
© www.soinside.com 2019 - 2024. All rights reserved.