Filter between dates using tidyverse lubridate in R

Viewed 626

I have a dataset of watertables and associated dates. I want to do something very simple: Mutate a column with seasons associated with the dates.

Example dataset:

Watertable date
2          2018-05-03
5          2018-08-01
12         2019-01-03
3          2019-07-29
4          2020-11-09
5          2021-08-22

Expected output:

Watertable date          season
2          2018-05-03    Spring
5          2018-08-01    Summer
12         2019-01-03    Winter
3          2019-07-29    Summer
4          2020-10-09    Fall
5          2021-08-22    Summer

The dates are converted to 'date' using the lubridate package. I can create the season column by mutating an extra column for only the month and days and using a case_when on that column, but this seems like an extra unnecessary step.

my question: how can i use mutate and case_when to create the new 'season' columnm, without having to create a new column with only the months and days. I.e. I want to use lubridate to select a period of dates omitting the year, because the new column is only depandant on the month and day value in the date.

I hope the question is clear. Happy to provide additional info when asked for.

starting dates seasons:
spring = 20 march
summer = 20 june
fall = 22 september
winter = 21 december
1 Answers

One way is to make the 'year' common among all the observations and then use case_when

library(dplyr)
library(lubridate)
df %>% 
    mutate(date1 =  as.Date(format(date, '2021-%m-%d')), 
        season = case_when(between(date1, ymd('2021-03-20'), ymd('2021-06-19'))
             ~ 'Spring',
      between(date1, ymd('2021-06-20'), ymd('2021-09-22'))
         ~ 'Summer', 
     between(date1, ymd('2021-09-22'), ymd('2021-12-21')) ~ 'Fall', 
       TRUE ~ 'Winter'), date1 = NULL)

-output

 Watertable       date season
1          2 2018-05-03 Spring
2          5 2018-08-01 Summer
3         12 2019-01-03 Winter
4          3 2019-07-29 Summer
5          4 2020-11-09   Fall
6          5 2021-08-22 Summer

data

df <- structure(list(Watertable = c(2L, 5L, 12L, 3L, 4L, 5L), date = structure(c(17654, 
17744, 17899, 18106, 18575, 18861), class = "Date")), row.names = c(NA, 
-6L), class = "data.frame")
Related