开发者

Creating a unique sequence of dates

开发者 https://www.devze.com 2023-04-06 22:15 出处:网络
Let\'s say that I want to generate a data frame which contains a column with is structured in the following format.

Let's say that I want to generate a data frame which contains a column with is structured in the following format.

2011-08-01
2011-08-02
2011-08-03
2011-08-04
...

I want to know if it's possible to generate this data with the seq() comm开发者_Go百科and.

Something like the following: (obviously doesn't work)

seq(2011-08-01:2011-08-31)

Would I instead have to use toDate and regex to generate this date in this specific format.


As I noted in my comment, seq has method for dates, seq.Date:

seq(as.Date('2011-01-01'),as.Date('2011-01-31'),by = 1)
 [1] "2011-01-01" "2011-01-02" "2011-01-03" "2011-01-04" "2011-01-05" "2011-01-06" "2011-01-07" "2011-01-08"
 [9] "2011-01-09" "2011-01-10" "2011-01-11" "2011-01-12" "2011-01-13" "2011-01-14" "2011-01-15" "2011-01-16"
[17] "2011-01-17" "2011-01-18" "2011-01-19" "2011-01-20" "2011-01-21" "2011-01-22" "2011-01-23" "2011-01-24"
[25] "2011-01-25" "2011-01-26" "2011-01-27" "2011-01-28" "2011-01-29" "2011-01-30" "2011-01-31"


I have made the same mistake with seq() attempting to make a numeric sequence. Don't use the ":" operator between arguments, and they will need to be dates if you want to make a date sequence. Another way is to take one date and add a numeric sequence starting with 0:

> as.Date("2000-01-01") + 0:10
 [1] "2000-01-01" "2000-01-02" "2000-01-03" "2000-01-04" "2000-01-05" "2000-01-06"
 [7] "2000-01-07" "2000-01-08" "2000-01-09" "2000-01-10" "2000-01-11"


You could try timeBasedSeq in the xts package. Notice the argument is a string and the use of the double-colon.

timeBasedSeq("2011-08-01::2011-08-31")


I had to generate a seq by min, and it was no easy, but i found seq.POSIXt in base. In your case, you want a seq of daily data from 2011-08-01 to 2011-08-31. So i suggest you

days <- seq(ISOdate(2011,8,1), by = "day", length.out = 31)
class(days)
"POSIXct" "POSIXt"


This worked for me! I know it's similar to the most upvoted answer, but that fact that i can specify "1 month" in text is amazing!

seq(as.Date("2012-01-01"),as.Date("2019-12-01"), by = "1 month")


You can use clock's date_build, which comes with nice functionalities and useful error message:

library(clock)
date_build(2011, 8, 1:31)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号