R Tips

Home

Contact

Steven Holland

Creating Julian Dates

3 November, 2009

When plotting something as a function of date, or doing calculations based on dates, it’s often useful to convert vectors of year, month, day, and time into a single value called the Julian date. The date library has useful functions for Julian date, so you'll need to install this on your computer first. Once you have it installed, you’ need to load it in any R session in which you want to use it. You can also put it in your startup file if you always need it.

Suppose you have a data file with separate columns for month (MM), day (DD), year (YYYY), and time of day (hh). Suppose also that these are sorted so that the oldest date is at the bottom and the youngest is at the top. Julian dates are relative to some starting date, so you could use your oldest date as the starting date and reference all of your dates relative to it. The mdy.date() function in the date library handles the conversion of the day, month, and year. The whole process looks like this:

library(date)
myData <- read.table(file="myData.txt", header=TRUE, sep=",")
attach(myData)
firstentry <- length(MM)
start <- mdy.date(MM[firstentry], DD[firstentry], YYYY[firstentry])
juliandate <- mdy.date(MM, DD, YYYY) - start + hh/24


The fourth line finds the oldest date in the last line of the data. The hh/24 in the last line of code adds the fractional number of hours in the day to the Julian date.