Creating a specific sequence of date/times in R
Solution 1
I would strongly recommend you to use the POSIXct
datatype. This way you can use seq
without any problems and use those data however you want.
start <- as.POSIXct("2012-01-15")
interval <- 60
end <- start + as.difftime(1, units="days")
seq(from=start, by=interval*60, to=end)
Now you can do whatever you want with your vector of timestamps.
Solution 2
Try this. mondate
is very clever about advancing by a month. For example, it will advance the last day of Jan to last day of Feb whereas other date/time classes tend to overshoot into Mar. chron
does not use time zones so you can't get the time zone bugs that code as you can using POSIXct. Here x
is from the question.
library(chron)
library(mondate)
start.time.num <- as.numeric(as.chron(x))
# +1 means one month. Use +12 if you want one year.
end.time.num <- as.numeric(as.chron(paste(mondate(x)+1, start.time)))
# 1/24 means one hour. Change as needed.
hours <- as.chron(seq(start.time.num, end.time.num, 1/24))
user1626688
Updated on June 16, 2022Comments
-
user1626688 almost 2 years
I want to create a single column with a sequence of date/time increasing every hour for one year or one month (for example). I was using a code like this to generate this sequence:
start.date<-"2012-01-15" start.time<-"00:00:00" interval<-60 # 60 minutes increment.mins<-interval*60 x<-paste(start.date,start.time) for(i in 1:365){ print(strptime(x, "%Y-%m-%d %H:%M:%S")+i*increment.mins) }
However, I am not sure how to specify the range of the sequence of dates and hours. Also, I have been having problems dealing with the first hour "00:00:00"? Not sure what is the best way to specify the length of the date/time sequence for a month, year, etc? Any suggestion will be appreciated.