user53020 user53020 - 9 months ago 48
R Question

R convert date without year into Julian day

I have some date that I need to convert into Julian days. This is the data I have

date <- c("21-Jul", "14-Jul", "08-Jul", "08-Jul","16-Jul")

[1] "character"

I want to convert
into julian days. So for the above dates, the Julian days will be:


I found a function
that converts date into Julian day. For e.g.

tmp <- as.POSIXlt("16Jun10", format = "%d%b%y")
# [1] 166

But this needs date in a particular order including year which I do not have. Is there any way to convert my dates which are characters and do not have year in it into Julian. Also this year is not a leap year.

Julian days imply day of the year so 1st Jan is 1, 2nd Jan is 2 and so on....

lmo lmo
Answer Source

base R has a function julian that can produce what you are looking for together with paste0 and as.Date.

julian(as.Date(paste0("1970-", date), format="%Y-%d-%b"))
[1] 201 194 188 188 196
[1] "1970-01-01"

Note that this is counted as number of days from January 1, 1970 (it starts at 0), so you can add 1 to get the desired result.

julian(as.Date(paste0("1970-", date), format="%Y-%d-%b")) + 1
[1] 202 195 189 189 197

I manually checked that 1970 is not a leap year:

seq(as.Date("1970-02-25"), as.Date("1970-03-02"), by="day")
[1] "1970-02-25" "1970-02-26" "1970-02-27" "1970-02-28" "1970-03-01" "1970-03-02"

For future reference, it is also possible to set the starting point yourself, using the origin argument to as.Date:

julian(as.Date(paste0("1980-", date), format="%Y-%d-%b"), origin=as.Date("1980-01-01"))
[1] 202 195 189 189 197
[1] "1980-01-01"

As should be clear, origin can be set to any date that you wish, so that this could be used to calculate the number of days following (or preceding) any date.