Date and Time in R

June 15, 2010

(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.
Notice that this function returns a Date object.
A string in this format is treated as a character unless cast to a Date type.
You can also pass in dates in other formats and cast them as strings by specifying the format in use.
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.
If you need a greater degree of time differentiation, the time (“POSIXlt” and “POSIXct”) is available as well.

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.
If you are working with time series data, the timeSeries library provides some convenient functionality.

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. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, 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.

Search R-bloggers


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)