BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
lansoprazole
Obsidian | Level 7

Hi all,

 

I have this table 

ID Var1Var2
1.6
128
1.9
2.1
2.3
2.5

 

I am trying to create a new dataset with ONE LINE for each ID and a new var (Var3) that its value depends on Var1 and Var2:

- If Var1 is missing, then Var3 = last Var 2 value ; else Var3 = Var1 

(Var3 for each ID will be either first non-missing Var1 or last Var2 value)

 

So the new dataset would look like

IDVar3
12
25

 

Thanks,

W

1 ACCEPTED SOLUTION

Accepted Solutions
Tom
Super User Tom
Super User

You can use the UPDATE statement for this problem.

data want;
   update have(obs=0) have;
   by id;
   var3 = coalesce(var1,var2);
run;

If you don't want the values of VAR2 retained (ie if VAR1 is all missing and the LAST value of VAR2 is missing means that then you want VAR3 to be missing even if earlier values of VAR2 were non-missing) then add an extra SET statement to re-read just VAR2 to replace any retained value.

data want;
   update have(obs=0) have;
   by id;
  set have(keep=var2);
   var3 = coalesce(var1,var2);
run;

View solution in original post

4 REPLIES 4
Shmuel
Garnet | Level 18
data want;
 set have;
 by ID;
      retain var3;
      keep ID var3;
      if first.ID then var3 = .;
      if var1 then var3 = var1;
      if last.id then do;
         if var1 = . then do; var3=var2; output; end;
else output; end; run;
lansoprazole
Obsidian | Level 7

Thanks for your reply.

I believe there should be an output statement once var3 takes the value of var1 and move to the second ID.

 

I tried your program but the result was:

ID Var3

1   9

2   5

Tom
Super User Tom
Super User

You can use the UPDATE statement for this problem.

data want;
   update have(obs=0) have;
   by id;
   var3 = coalesce(var1,var2);
run;

If you don't want the values of VAR2 retained (ie if VAR1 is all missing and the LAST value of VAR2 is missing means that then you want VAR3 to be missing even if earlier values of VAR2 were non-missing) then add an extra SET statement to re-read just VAR2 to replace any retained value.

data want;
   update have(obs=0) have;
   by id;
  set have(keep=var2);
   var3 = coalesce(var1,var2);
run;
lansoprazole
Obsidian | Level 7

Thanks!! 

That worked. 

 

W

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 968 views
  • 0 likes
  • 3 in conversation