How to generate time intervals or date sequence in R

time intervals and date sequence in R

In this post, you will get summary and code examples for creating time intervals, date or date-time sequence different ways in R.

For example, you have to make summary statistics for 15 minute time intervals in R. There might be situations wherein a 15 minute interval is no data. It is necessary to, first of all, generate theoretical hour and minute sequence and then join with actual data. Notice that for actual data sometimes it is necessary to detect last full-time interval.

For that task, you will need chron and lubridate libraries and some of the base functions like merge and seq.

Hour and minute (time) intervals

In my case, there is 15 minute sequence that I’m creating with seq(0, 45, by = 15) and merging with hour vector. By merging two vectors, you have a data frame with two columns with names x, y all possible combinations.

With paste function, you can combine them in something that looks like time and convert it to times class with chron function from chron package.

You can also put those time intervals in the data frame and order.

Last full time interval

If there is need to work with today’s data and you have data from a certain minute interval that is not ended, then sometimes you need to calculate last time full interval. For example, to subset data that will not change.

There are two functions from lubridate library floor_date and ceiling_date for rounding to the nearest time unit. In my case, I round down to nearest 15 minute interval, but last fully closed time interval is 15 minutes before, and that is the reason why I’m subtracting 900 (seconds).

Time from date time

You can also return only time portion and covert to times class with chron if necessary.

Date sequence

Sometimes you have to combine date sequence and earlier created time intervals. You can create a date sequence in R easily with base function.

You can also make a date sequence with the help of lubridate library, but it looks a little bit slower.

If you want to build a dynamic date sequence in R (based on today’s date), for example, for the last 7 days, it goes like this.

Date and time interval sequence

There is nothing much to say – combine previous techniques. After merging date sequence and time intervals, change column names. Combine date and time together and make it right order. I also made reset for row numbers after ordering.

Here is all the code


1 comment on “How to generate time intervals or date sequence in R

Leave a Reply

Your email address will not be published. Required fields are marked *