輸入
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"),但我無法找到實作輸出的這種方法。
uj5u.com熱心網友回復:
像這樣?
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
使用reprex v2.0.2創建于 2022-10-30
或與findInterval.
findInterval(dates, seq(min(dates), max(dates), by = "10 days"))
#> [1] 1 2 2 3
使用reprex v2.0.2創建于 2022-10-30
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524898.html
標籤:r日期
