gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:30:35 24 4
gpt4 key购买 nike

我有这样的数据:

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 获取最近六个月的数据?我想要的是从“2021-06-01”到“2021-09-30”的完整数据。谢谢。

最佳答案

我们可以获取“datex”的max值,创建一个6或3个月的sequnece,seq向后,并创建带有“datex”的逻辑向量来过滤

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

关于r - 如何在R中使用dplyr获取最近三个月的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69490543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com