DATA Step, Macro, Functions and more

using first. with multiple by variables and assigning a value in new variable

Accepted Solution Solved
Reply
Occasional Contributor V_R
Occasional Contributor
Posts: 5
Accepted Solution

using first. with multiple by variables and assigning a value in new variable

I have a data set like following

data have;
informat date1 date9.;
format date1 date9.;
input date1 id flag$;
cards;
21jan2018 1 n
21jan2018 1 y
21jan2018 1 y
22jan2018 1 y
22jan2018 1 y
22jan2018 1 y
22jan2018 2 n
22jan2018 2 y
22jan2018 2 y
22jan2018 2 y
22jan2018 2 y
;
run;

I want to add a flag1 such that same date and same id flag1 will take value of flag and retain that value for same date and id.

once id got change in same date then flag 1 should have value of flag and retain that value for same date and id

once date gets changes again code should assign value of flag to flag1 and retain that value for date and id

I want an output like following

Date ID Flag Flag1

21jan2018 1 n n
21jan2018 1 y n
21jan2018 1 y n
22jan2018 1 y y
22jan2018 1 y y
22jan2018 1 y y
22jan2018 2 n n
22jan2018 2 y n
22jan2018 2 y n
22jan2018 2 y n
22jan2018 2 y n

I tried using following code but not successful.


data test1;
set test;
by date1 id flag;
retain flag1;
if first.date1  then do;
if first.id then do;
if flag ne "n" then flag1 = "y";
else if flag eq "n" then flag1 = "n";
end;
end;
run;

please help

 

Regards,

VR


Accepted Solutions
Solution
‎02-04-2018 10:14 PM
Esteemed Advisor
Posts: 5,398

Re: using first. with multiple by variables and assigning a value in new variable

[ Edited ]

All you need is:

 

data test1;
set test;
by date1 id;
retain flag1;
if first.id then flag1 = flag;
run;

first.id is = 1 whenever date1 OR id changes.

 

PG

View solution in original post


All Replies
Solution
‎02-04-2018 10:14 PM
Esteemed Advisor
Posts: 5,398

Re: using first. with multiple by variables and assigning a value in new variable

[ Edited ]

All you need is:

 

data test1;
set test;
by date1 id;
retain flag1;
if first.id then flag1 = flag;
run;

first.id is = 1 whenever date1 OR id changes.

 

PG
Occasional Contributor V_R
Occasional Contributor
Posts: 5

Re: using first. with multiple by variables and assigning a value in new variable

Thanks for your help.

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 2 replies
  • 197 views
  • 0 likes
  • 2 in conversation