Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fill a column with one of four date columns based on another R

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading