I have a vector of dates and for each entry, I would like to assign a season. So for example, if a date is between 21.12. and 21.3., I would says that's winter
. So far I have tried the following code but I couldn't make it more generic, irrespective of the year.
my.dates <- as.Date("2011-12-01", format = "%Y-%m-%d") + 0:60
low.date <- as.Date("2011-12-15", format = "%Y-%m-%d")
high.date <- as.Date("2012-01-15", format = "%Y-%m-%d")
my.dates[my.dates <= high.date & my.dates >= low.date]
[1] "2011-12-15" "2011-12-16" "2011-12-17" "2011-12-18" "2011-12-19" "2011-12-20" "2011-12-21" "2011-12-22" "2011-12-23" "2011-12-24" "2011-12-25"
[12] "2011-12-26" "2011-12-27" "2011-12-28" "2011-12-29" "2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03" "2012-01-04" "2012-01-05"
[23] "2012-01-06" "2012-01-07" "2012-01-08" "2012-01-09" "2012-01-10" "2012-01-11" "2012-01-12" "2012-01-13" "2012-01-14" "2012-01-15"
I have tried formatting the dates without the year, but it isn't working.
ld <- as.Date("12-15", format = "%m-%d")
hd <- as.Date("01-15", format = "%m-%d")
my.dates[my.dates <= hd & my.dates >= ld]
Here a more general solution, that nevertheless needs 3 libraries... It considers all years and the hemisphere:
I would create a lookup table, and go from there. An example (note the code obfuscation using the
d()
function and the pragmatic way of filling the lut):After creating the lookup table, you can extract quite easily from it to what season a month/day combination belongs to:
All nice and vectorized :). I think once the table is created, this is very quick.
I think this would do it, but it's an ugly solution:
My solution is not fast but is flexible about the starts of the seasons as long as they are defined in a dataframe first for the function
assignSeason
. It requires magrittr for the piping functions, lubridate for theyear
function, and dplyr formutate
.Example data:
Result:
Simply use time2season function. It gets date and generates season:
You can find more infromation here.
I have something similarly ugly as Tim:
And here is a test: