Date and Time in R

[This article was first published on R-Chart, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.


The following are a few date and time functions that I needed to figure out early on when working with R.

We will start when we are… the current system date.

Sys.Date()

Notice that this function returns a Date object.

class(Date)

A string in this format is treated as a character unless cast to a Date type.

class(“2010-06-16”)
class(as.Date(“2010-06-16”))

You can also pass in dates in other formats and cast them as strings by specifying the format in use.

as.Date(’02/03/2004′,’%m/%d/%Y’)

To format date information in a wide variety of string formats, use the strftime function.

strftime(Sys.Date(),’%A: %B %d, %Y (Day %j of %Y)’)

This returns the string “Tuesday: June 15, 2010 (Day 166 of 2010)”

Dates can be manipulated arithmetically. To return the next ten days…

seq(Sys.Date(),Sys.Date() + 10,1)

…or the last ten days…

seq(Sys.Date(),Sys.Date() – 10,-1)

There are number of packages with special date and time functionality. For example, to find out the holidays for the New York Stock Exchange.

library(timeDate)
holidayNYSE()

If you need a greater degree of time differentiation, the time (“POSIXlt” and “POSIXct”) is available as well.

Sys.time()

Much more can be said about dates and times, particularly if you delve into time series plotting and analysis. Please comment on any additional date time functionality that you use in R.

UPDATE
If you are working with time series data, the timeSeries library provides some convenient functionality.

library(timeSeries)
timeSequence(from=”2010-03-01″, to=”2010-03-03″, by=”day”)
timeSequence(from=”2010-03-01″, to=”2010-03-02″, by=”hour”)

The xts and zoo packages seem be the standard for time sequence plotting and analysis.

To leave a comment for the author, please follow the link and comment on their blog: R-Chart.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)