Mutate using Date Column

Hello everyone!

Suppose that I have 2019 data with the average daily revenues of a small business. So there are 365 rows in the data representing each day in a year (i.e., there are 365 days in a year), and it looks something like this:

Day Date Revenue
1 2019-01-01 1700
2 2019-01-02 1400
3 2019-01-03 1800
4 2019-01-04 900
5 2019-01-05 2000
. . .
. . .
. . .
364 2019-12-30 3000
365 2019-12-31 3800

I wanna create another column called "Season" using the mutate function. More specifically, the December 1 to February 31 would be labeled "Winter", March 1 to May 31 would be "Spring", June 1, to August 31 would be "Summer", and September 1 to November 31 would be "Fall." So I wanna create something like this:

Day Date Revenue Season
1 2019-01-01 1700 Winter
2 2019-01-02 1400 Winter
3 2019-01-03 1800 Winter
4 2019-01-04 900 Winter
5 2019-01-05 2000 Winter
. . .
. . .
59 2019-03-01 1900 Spring
60 2019-03-02 1850 Spring
. . .
. . .
151 2019-06-01 2100 Summer
152 2019-06-02 2000 Summer
. . .
. . .
243 2019-09-01 2300 Fall
244 2019-09-02 1900 Fall
. . .
. . .
364 2019-12-30 3000 Winter
365 2019-12-31 3800 Winter

So anybody know how to do this? I reckon this would be quite simple, but I have never used the mutate function using the date, so I'm not sure how to do this.

Thank you,

This is a really good use case for dplyr::case_when. I would do something like this:

data %>% 
    mutate(
        season = case_when(
            lubridate::month(date) %in% c(12, 1, 2) ~ 'Winter',
            lubridate::month(date) %in% 3:5 ~ 'Spring',
            lubridate::month(date) %in% 6:8 ~ 'Summer',
            lubridate::month(date) %in% 9:11 ~ 'Fall'
        )
    )

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.