NewUsr_stat
NewUsr_stat

Reputation: 2583

Replace values in a column with values in another column if not missings

suppose to have the following:

    Date1           Date2          
  01JAN2021           .
  01FEB2021           .      
  01JAN2021       07JAN2021
  07MAR2020       09MAR2021   
  08JUL2022           .
  .........       .........       

In other words when there is an observation in variable Date2 the observation in variable Date1 must be replaced by the one in Date2 as follows:

    Date1                  
  01JAN2021          
  01FEB2021        
  07JAN2021       
  09MAR2021        
  08JUL2022         
  .........       

Can anyone help me please? I tried merge but it does not replace. Maybe the right way could be to replace the Date2 column entirely with Date1 but I don't know how to code it. I tried to do:

if date2-date1=0 then do date_new=date1 else date_new=date2

but it simply gives date_new==date2 with missings.

Best

Upvotes: 0

Views: 1119

Answers (2)

Richard
Richard

Reputation: 27526

If you have more than two date-n fields, you can use a reverse index variable list with COALESCE

data want;
  set have;
  date1 = coalesce(of date9-date1);
run;

Upvotes: 1

PeterClemmensen
PeterClemmensen

Reputation: 4937

Do this

data have;
input (Date1 Date2)(:date9.);
format Date1 Date2 date9.;
datalines;
01JAN2021 .         
01FEB2021 .         
01JAN2021 07JAN2021 
07MAR2020 09MAR2021 
08JUL2022 .         
;

data want;
   set have;
   Date1 = coalesce(Date2, Date1);
run;

Upvotes: 3

Related Questions