1
votes

I have a data set in R that contains a column of dates in the format yyyy/mm/dd. I am trying to use as.Date to convert these dates to date objects in R. However, I cannot seem to find the correct argument for origin to input into as.Date. The following code is an example of what I have been trying. I am using a CSV file from Excel, so I used origin="1899/12/30 based on other sites I have looked at.

> as.Date(2001/04/26, origin="1899/12/30")

 [1] "1900-01-18"

However, this is not working since the input date 2001/04/26 is returned as "1900-01-18". I need to convert the dates into date objects so I can then convert the dates into julian dates.

1
I think your looking for format instead of origin, try as.Date("2001/04/26", "%Y/%m/%d")Jilber Urbina

1 Answers

0
votes

You can either is as.Date with a numeric value, or with a character value. When you type just 2001/04/26 into R, that's doing division and getting 19.24 (a numeric value). And numeric values require an origin and the number you supply is the offset from that origin. So you're getting 19 days away from your origin, ie "1900-01-18". A date like Apr 26 2001 would be

as.Date(40659, origin="1899-12-30")
# [1] "2011-04-26"

If your dates from Excel "look like" dates chances are they are character values (or factors). To convert a character value to a Date with as.Date() you want so specify a format. Here

as.Date("2001/04/26", format="%Y/%m/%d")
# [1] "2001-04-26"

see ?strptime for details on the special % variables. Now if you're read your data into a data.frame with read.table or something, there's a chance your variable may be a factor. If that's the case, you'll want do convert to character with'

as.Date(as.character(mydf$datecol), format="%Y/%m/%d")