簡體   English   中英

使用 R 計算特定時期內每個可能的時間范圍

[英]Calculate every possible time range in a specific period using R

如何使用 R 計算特定時期內每個可能的時間范圍?

例子

時間段:2021-01-01 - 2021-06-30

開始日期 結束日期
2021-01-01 2021-01-01
2021-01-01 2021-01-02
2021-01-01 2021-01-03
2021-01-01 2021-01-04
... ...
2021-01-02 2021-01-02
2021-01-01 2021-01-03
2021-01-01 2021-01-04
2021-01-01 2021-01-05
... ...

條件:開始日期必須始終早於或等於結束日期

有任何想法嗎?

最好的,詹尼克

start = as.Date("2021-01-01")
end = as.Date("2021-06-30")
## get all the dates in the range
seq = seq(start, end, by = "day")
## produce all unique combinations of 2 dates
pairs = t(combn(seq, 2))
## verify they are already correctly ordered
all(pairs[, 1] < pairs[, 2])
# [1] TRUE

## put them in a data frame and convert back to date
## (the `combn` step produced a matrix and lost the Date class...)
pairs = as.data.frame(pairs)
pairs[] = lapply(pairs, as.Date, origin = "1970-01-01")
names(pairs) = c("start", "end")

## examine the first few rows
head(pairs)
#        start        end
# 1 2021-01-01 2021-01-02
# 2 2021-01-01 2021-01-03
# 3 2021-01-01 2021-01-04
# 4 2021-01-01 2021-01-05
# 5 2021-01-01 2021-01-06
# 6 2021-01-01 2021-01-07

dim(pairs)
# [1] 16290     2

這不包括從日期到其本身的范圍,如您的第一行。 如果你想要包含這些,你可以在最后加上它們:

rbind(pairs, data.frame(start = seq, end = seq))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM