[R] dates() is a great date function in R

Mr Natural drstrong at ucdavis.edu
Wed Jul 18 21:14:47 CEST 2007


Proper calendar dates in R are great for plotting and calculating. 
However for the non-wonks among us, they can be very frustrating.
I have recently discussed the pains that people in my lab have had 
with dates in R. Especially the frustration of bringing date data into R 
from Excel, which we have to do a lot. 

Please find below a simple analgesic for R date importation that I
discovered 
over the last 1.5 days (Learning new stuff in R is calculated in 1/2 days).

The function    dates()    gives the simplest way to get calendar dates into
R from Excel that I can find.
But straight importation of Excel dates, via a csv or txt file, can be a a
huge pain (I'll give details for anyone who cares to know). 

My pain killer is:
Consider that you have Excel columns in month, day, year format. Note that R
hates date data that does not lead with the year. 

a. Load the chron library by typing   library(chron)   in the console.
You know that you need this library from information revealed by 
performing the query,
?dates()"    in the Console window. This gives the R documentation 
help file for this and related time, date functions.  In the upper left 
of the documentation, one sees "dates(chron)". This tells you that you
need the library chron. 

b. Change the format "dates" in Excel to format "general", which gives 
5 digit Julian dates. Import the csv file (I use    read.csv()  with the 
Julian dates and other data of interest.

c.  Now, change the Julian dates that came in with the csv file into 
calendar dates with the    dates() function. Below is my code for performing 
this activity, concerning an R data file called ss,

ss holds the Julian dates, illustrated below from the column MPdate,

>ss$MPdate[1:5]
[1] 34252 34425 34547 34759 34773

The dates() function makes calendar dates from Julian dates,

>dmp<-dates(ss$MPdate,origin=c(month = 1, day = 1, year = 1900))

> dmp[1:5]
[1] 10/12/93 04/03/94 08/03/94 03/03/95 03/17/95

I would appreciate the comments of more sophisticated programmers who
can suggest streamlining or shortcutting this operation.

regards, Don



 
-- 
View this message in context: http://www.nabble.com/dates%28%29-is-a-great-date-function-in-R-tf4105322.html#a11675205
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list