I'd like to create a new variable that is dependent on other variables, rowwise. For certain months and years, I want to specify a certain value that varible takes. For other months and years, I want the variable to take a date value from other column.
df <- df %>% mutate(start_of_risk = case_when(
month == 8 & year == 2010 ~ "2010-10-01",
month == 9 & year == 2010 ~ "2010-10-01",
month == 3 & year == 2011 ~ date))
However, when I try this the following error appears:
Error in `mutate()`: ℹ In argument: `start_of_risk = case_when(...)`.
Caused by error in `case_when()`: ! Can't combine `..1 (right)`
<character> and `..8 (right)` <date>. Backtrace:
1. df %>% ...
9. dplyr::case_when(...)
Is it possible to use a date in case_when() or is there a way around this?
As stated as a comment, you have a mis-match in the class of the possible responses. Try
df <- df %>% mutate(start_of_risk = case_when(
month == 8 & year == 2010 ~ as.Date("2010-10-01"),
month == 9 & year == 2010 ~ as.Date("2010-10-01"),
month == 3 & year == 2011 ~ date))
If you are still getting errors with this change, we would need to see what the date
variable looks like to give a more detailed response.