如何在r中使用dplyr获取最近三个月的数据



我有这样的数据:

library(lubridate)
library(dplyr)
set.seed(2021)
gen_date <- seq(ymd_h("2021-01-01-00"), ymd_h("2021-09-30-23"), by = "hours")
hourx <- hour(gen_date)
datex <- date(gen_date)
sales <- round(runif(length(datex), 10, 50), 0)*100
mydata <- data.frame(datex, hourx, sales)

如何使用dplyr获得最近三个月的数据?或者我如何使用dplyr获得过去六个月的数据?我想要的是来自"20121-06-01"的完整数据。";2021 - 09 - 30 -"。谢谢你。

我们可以得到'datex'的max值,将seq反向创建一个6或3个月的seq序列,并创建一个'datex'到filter的逻辑向量

library(dplyr)
n <- 6
out <- mydata %>% 
filter(datex >= seq(floor_date(max(datex), 'month'),
length.out = n + 1, by = '-1 month'))

检查

> head(out)
datex hourx sales
1 2021-03-01     4  5000
2 2021-03-01    11  3200
3 2021-03-01    18  1500
4 2021-03-02     1  4400
5 2021-03-02     8  4400
6 2021-03-02    15  4400

> max(mydata$datex)
[1] "2021-09-30"

3个月

n <- 3
out2 <- mydata %>% 
filter(datex >= seq(floor_date(max(datex), 'month'),
length.out = n + 1, by = '-1 month'))
> head(out2)
datex hourx sales
1 2021-06-01     3  2100
2 2021-06-01     7  1300
3 2021-06-01    11  4800
4 2021-06-01    15  1500
5 2021-06-01    19  3200
6 2021-06-01    23  3400

你可以试试

library(xts)
x <- mydata %>%
mutate(month = month(datex)) %>%
filter(month %in% last(unique(month), 3))
unique(x$month)
[1] 7 8 9

最新更新