Date and Time in R

June 15, 2010
By

(This article was first published on R-Chart, and kindly contributed to R-bloggers)


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 his blog: R-Chart.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: ,

Comments are closed.