Raul
Raul

Reputation: 271

Using case_when to categorize a variable by date ranges?

I currently have a list of transactions and I would like to add a categorical value to each of them depending on the age of the transaction. Sample Data:

Date    Transaction 
9/2/2020    44
8/29/2020   65.3
8/29/2020   34
8/29/2020   195
8/28/2020   180
8/28/2020   195
8/28/2020   48
8/27/2020   195
8/27/2020   65.3
8/27/2020   77

Pseudocode:

today<- lubridate::day(Sys.Date())
mutate(Age= case_when(
                         Date between(today, today -7) ~ "< Week Old",
                         Date between(today, today -30) ~ "30days Old",
                         Date between(today, today -60) ~ "60days Old",
                         Date >= between(today, today -90) ~ "90days+ Old"))

Is it possible to filter data in a mutate using between for date ranges?

#Currently familiarizing and exploring the cut suggestion, thanks

Upvotes: 1

Views: 1958

Answers (1)

tamtam
tamtam

Reputation: 3671

Your first try with case_when was a good idea. But you used the between and day function not in the right way. Maybe try this:

today <- lubridate::today()

df %>% 
  mutate(Age = case_when(
   between(Date, today-7, today) ~ "< Week Old",
   between(Date, today-30, today) ~ "30days Old",
   between(Date, today-60, today) ~ "60days Old",
   TRUE ~ "90days+ Old"))

Upvotes: 2

Related Questions