I have a DF with 5 columns like so;
A B Date1 Date2 Date3 Date4
1 x NA NA NA
2 NA y NA NA
3 NA NA z NA
4 NA NA NA f
I want to use the dplyr package and the case_when() function to state something like this
df <- df %>%
mutate(B = case_when(
A == 1 ~ B == Date1,
A == 2 ~ B == Date2,
A == 3 ~ B == Date3,
A == 4 ~ B == Date4))
Essentially based on the value of A I would like to fill B with one of 4 date coloumns.
A is of class character, B and the Date are all class Date.
Problem is when I apply this to the dataframe it simply doesn’t work. It returns NAs and changes the class of B to boolean. I am using R version 4.1.2. Any help is appreciated.
>Solution :
The other answers are superior, but if you must use your current code for the actual application, the corrected version is:
df %>%
mutate(B = case_when(
A == 1 ~ Date1,
A == 2 ~ Date2,
A == 3 ~ Date3,
A == 4 ~ Date4))
Output:
# A B Date1 Date2 Date3 Date4
# 1 x x <NA> <NA> <NA>
# 2 y <NA> y <NA> <NA>
# 3 z <NA> <NA> z <NA>
# 4 f <NA> <NA> <NA> f