Gary Lynam
Gary Lynam

Reputation: 3

R: Convert list of character dates to "days since" a given origin

I need to generate a list to attach as a time dimension for a NetCDF file. This file was stacked from many files that were generated as monthly means from 6-hourly data. As a result, each t observation is simply the chronological value of the file in the stack.

First, I generated a date sequence, converted it to characters and then created a date object stating the origin to be the origin of interest. My objective was to receive an integer list of "days since 1850-01-01", however, converting to an integer, I see the origin used is still the R default "1970-01-01".

I am new to working with this "Julian" approach and I would appreciate any advice as to what methods I should use.

The code is as follows

dates <- seq(as.Date("1901-01-01"), by = "month", length.out = 12)
dates <- as.character(dates)

o <- as.Date("1850-01-01")

dates <- as.Date(dates, origin = o)
dates
dates <- as.numeric(dates)

Upvotes: 0

Views: 1025

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269674

Convert dates to Date class, subtract o and convert that to numeric:

as.numeric(as.Date(dates) - o)
## [1] 18627 18658 18686 18717 18747 18778 18808 18839 18870 18900 18931 18961

Alternately convert both to numeric:

as.numeric(as.Date(dates)) - as.numeric(o)

or use difftime

as.numeric(difftime(as.Date(dates), o, unit = "day"))

Upvotes: 1

Related Questions