0

I tried using the lubridate::floor_date function to get the first date of the season in which my input date is, for ex.:

x <- ymd_hms("2008-08-03 12:01:59.23")

this date is in the summer of 2008, so starting 21-06-2008 and ending 20-09-2008. According to this i expected that by running this

lubridate::floor_date(x, "season")

i would get this

21-06-2008

but instead i get this

"2008-06-01 UTC"

which is not the beginning of the summer of 2008.

Am I using the wrong function, or is there another way to achieve what I'm trying to get ?

enter image description here

SamR
  • 8,826
  • 3
  • 11
  • 33
adl
  • 1,390
  • 16
  • 36
  • Doesn't summer starts at June 1st? – Park Jul 25 '22 at 06:27
  • noup, usually it starts on the 21st or 22nd of June – adl Jul 25 '22 at 06:29
  • 1
    there is a difference between "Astronomical Season" (eg June 21st) and "Meteorological season" (eg June 1st). One suggestion would be: https://stackoverflow.com/a/9501225/8598377 – Stephan Jul 25 '22 at 06:44
  • i believe i asked a question at the end: "is there another way to achieve what im trying to get ?" - i will change the title of the question so that its not misleading – adl Jul 25 '22 at 09:10
  • Thanks I have retracted my close flag now. – SamR Jul 25 '22 at 10:09

1 Answers1

1

As you are using lubridate then you can create a function using floor_date().

astronomical_floor <- function(x) {
    stopifnot(
        (is(x, "Date") | is(x, "POSIXct") | is(x, "POSIXt"))
    )

    astronomical_floor <- x |>
        floor_date("season") |>
        format("%Y-%m-21") |>
        ymd()

    # Make sure floor not greater than date
    # e.g. 2022-06-05 should return 2022-03-21
    # not 2022-06-21
    if (astronomical_floor > x) {
        astronomical_floor <- floor_date(
            x %m+% months(-1)
        ) |>
            floor_date("season") |>
            format("%Y-%m-21") |>
            ymd()
    }

    return(astronomical_floor)
}


x <- ymd_hms("2008-08-03 12:01:59.23")
astronomical_floor(x) # "2008-06-21"
astronomical_floor(as.Date("2020-01-01")) # "2019-12-21"
astronomical_floor(x = ymd("2022-06-05")) # "2022-03-21"
SamR
  • 8,826
  • 3
  • 11
  • 33