I’m stucked trying to create a code that filters 5 consecutive days from a vector of dates starting from a given start date, across multiple years.
Example:
v = seq.Date(as.Date("2000-01-01"), as.Date("2020-12-31"), 1)
initial_date = as.Date("01-01") #(mm:dd)
Expected output:
2000-01-01 #(YYYY:mm:dd)
2000-01-02
2000-01-03
2000-01-04
2000-01-05
2001-01-01
2001-01-02
2001-01-03
2001-01-04
2001-01-05
...
2020-01-01
2020-01-02
2020-01-03
2020-01-04
2020-01-05
If the initial date is, for example, 12-31 (mm:dd), the result should be:
2000-12-31
2001-01-01
2001-01-02
2001-01-03
2001-01-04
2001-31-12
2002-01-01
2002-01-02
2002-01-03
2002-01-04
...
2019-12-31
2020-01-01
2020-01-02
2020-01-03
2020-01-04
2020-12-31
Any tips?
>Solution :
This function converts your "mm-dd" to a Date to find the next 5 days, then uses strftime(format = "%m-%d") to compare dates while ignoring the year.
get_days <- function(dates, mmdd, n = 5) {
wanted <- strftime(as.Date(paste0("1900-", mmdd)) + seq(n) - 1,"%m-%d")
dates <- dates[match(wanted[[1]], strftime(dates, "%m-%d")):length(dates)]
dates[strftime(dates, "%m-%d") %in% wanted]
}
get_days(v, "12-31")
# [1] "2000-12-31" "2001-01-01" "2001-01-02" "2001-01-03" "2001-01-04" "2001-12-31"
# [7] "2002-01-01" "2002-01-02" "2002-01-03" "2002-01-04" "2002-12-31" "2003-01-01"
# ...
# [91] "2018-12-31" "2019-01-01" "2019-01-02" "2019-01-03" "2019-01-04" "2019-12-31"
# [97] "2020-01-01"
The second line using match() excludes elements of v where the "index" "mm-dd" is before the start of the vector. e.g., "2000-01-01" is excluded since "1999-12-31" isn’t in v.