Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

r - Simulate multiple dates between two dates

library(lubridate)
date1<-ymd("2021/01/01")

date2<-ymd("2021/01/31")

How can I simulate multiple dates between "2021-01-01" and "2021-01-31", for example ten dates like this:

[1] "2021-01-21" "2021-01-07" "2021-01-09" "2021-01-18" "2021-01-02" "2021-01-13" "2021-01-24" "2021-01-30" "2021-01-11" "2021-01-25"
question from:https://stackoverflow.com/questions/65837632/simulate-multiple-dates-between-two-dates

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use seq(), e.g.

library(lubridate)
date1<-ymd("2021/01/01")
date2<-ymd("2021/01/31")
seq(date1, date2, length.out = 10)
>[1] "2021-01-01" "2021-01-04" "2021-01-07" "2021-01-11"
>[5] "2021-01-14" "2021-01-17" "2021-01-21" "2021-01-24"
>[9] "2021-01-27" "2021-01-31"

If you want 10 random dates:

library(lubridate)
date1<-ymd("2021/01/01")
date2<-ymd("2021/01/31")
dates <- seq(date1, date2, 1)
sample(dates, 10)
>[1] "2021-01-08" "2021-01-03" "2021-01-20" "2021-01-27"
>[5] "2021-01-02" "2021-01-17" "2021-01-19" "2021-01-30"
>[9] "2021-01-11" "2021-01-05"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...