0
data1 %>% 
mutate(generation = case_when(
 DOB %in% '1/1/1945' > '31/12/1967' ~ "baby_boomers"
 TRUE ~ "else" 
)

Could someone please show me the correct way to code a case when with dates (but formatted in DOB = col_character(),)

shafee
  • 15,566
  • 3
  • 19
  • 47
  • 1
    Welcome to Stack Overflow. Please [make this question reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) by including a small representative dataset in a plain text format - for example the output from `dput(data1)`, if that is not too large. Your current code won't work because `%in%` takes a vector as input and including `>` is incorrect syntax. Are you trying to see whether a date falls between two other dates? – neilfws Oct 13 '22 at 00:21
  • 2
    And you need to put your dates in the standard `"YYYY-MM-DD"` format. `DOB > '1945-01-01' & DOB < '1967-12-31' ~ "baby_boomers"` – Gregor Thomas Oct 13 '22 at 02:02
  • 1
    (If you don't use standard date formats, then you can't use `>` and `<`. Your `DOB` can be in character class if you use a `YYYY-MM-DD` format because then alphabetical ordering is the same as date ordering. But `m/d/yyyy` won't work.) – Gregor Thomas Oct 13 '22 at 02:03
  • Thanks Gregor, I changed the format to date (YYMMDD) and now says Error: unexpected symbol in: " new_DOB >'1945/01/01' & new_DOB < '1967/12/31' ~ "baby_boomer" (I change DOB to new_DOB with date format) – Sultan of swing Oct 14 '22 at 01:55
  • data1 %>% mutate(generation = case_when( new_DOB >='1945/01/01' & new_DOB <= '1967/12/31' ~ "baby_boomer", new_DOB >= '1968/01/01' & new_DOB <= '1984/12/31' ~ "GenX", new_DOB >= '1985/1/01' & new_DOB <= '1997/12/31' ~ "Millennials", TRUE ~ "GenZ" )) problem solved, thanks guys – Sultan of swing Oct 14 '22 at 02:17

0 Answers0