5

I need your help and thanks for anyone who will consider my request.

I would like to convert a Date column (class = date) of my dataframe into days since the earliest date of observation, starting from 1966-10-01 to 2006-09-30 included. Therefore, each day of observation should have one unique value, which, for 40 years should range from 1 to 14640 (40 * 366).

Here part of my Date column:

Date
17/12/1966
05/05/1968
30/10/1968
16/08/1970
07/01/1971
25/11/1971
29/09/1973
18/01/1974
17/09/1975
06/01/1976
28/11/1976
04/07/1978
15/11/1978
27/07/1980
20/09/1981
03/10/1981
11/09/1983
23/09/1984
25/10/1984
03/12/1985
07/12/1986

[...]

Any help would be really apreciated. Thanks

Dave2e
  • 22,192
  • 18
  • 42
  • 50
  • Possible duplicate of [Convert a date vector into Julian day in R](http://stackoverflow.com/questions/21414847/convert-a-date-vector-into-julian-day-in-r) – ytk Jun 28 '16 at 14:57
  • thanks, just modified the question. –  Jun 28 '16 at 15:40

2 Answers2

5

Base R has a Julian function with an option to specify the origin:

#example
date<-as.Date("2016-06-27")

#base R
result<-julian(date, origin=as.Date("1966-10-01"))
result
#[1] 18167
#attr(,"origin")
#[1] "1966-10-01"

as.numeric(result)
#18167
Dave2e
  • 22,192
  • 18
  • 42
  • 50
4

This should work:

library(lubridate)
ref_date <- dmy('01-10-1966')
new_date <- dmy('17/12/1966')
day_number <- as.numeric(difftime(new_date, ref_date))

EDIT:

That was an example; to apply directly to your dataset, use:

df$day_number <- as.numeric(difftime(df$Date, ref_date)) 
mkt
  • 437
  • 7
  • 20
  • hi, yes it works..but only for the date 17/12/1966 and therefore I have got only one Julian day. How can I extend it to the whole Date column? Thanks –  Jun 28 '16 at 15:03
  • df$day_number <- as.numeric(difftime(df$Date, ref_date)) – mkt Jun 28 '16 at 15:07
  • Sure thing! Happy to help. – mkt Jun 29 '16 at 07:34