输入
dates <- as.Date(c("2022-01-20", "2022-01-30", "2022-01-31", "2022-02-10"))
n <- 10 # number of days for each period
输出
group <- c(1, 2, 2, 3)
组 1
对应于最早日期以及距向量最早日期最多 n - 1
天的日期。
可以将每个日期转换为其天数(从 1900 年开始?)并使用 %/%
运算符,但我想要一个更合适的解决方案。
另一个解决方案是使用 seq(min(dates), max(dates), by = "10 days")
但我无法找到这样的方法来实现输出.
最佳答案
像这样吗?
dates <- as.Date(c("2022-01-20", "2022-01-30", "2022-01-31", "2022-02-10"))
n <- 10 # number of days for each period
as.integer(factor(as.integer(dates) %/% n))
#> [1] 1 2 2 3
创建于 2022 年 10 月 30 日 reprex v2.0.2
或者使用findInterval
。
findInterval(dates, seq(min(dates), max(dates), by = "10 days"))
#> [1] 1 2 2 3
创建于 2022 年 10 月 30 日 reprex v2.0.2
关于r - 如何在R中按n天的时间段对日期进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74251482/