Search code examples
rdatejulian-date

Convert date without year into Julian day (number of days since start of the year)


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")
class(date)

[1] "character"

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

date
202,195,189,189,197 

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

tmp <- as.POSIXlt("16Jun10", format = "%d%b%y")
tmp$yday
# [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 the day of the year so 1st Jan is 1, 2nd Jan is 2 and so on....


Solution

  • 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
    attr(,"origin")
    [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
    attr(,"origin")
    [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.