I need to create a counter variable field (rtn_int) that resets to zero when a field value condition is not met. Here is the data set:
AccountNumber PmtNumber RtnType
1001 1 Non-R01
1001 2 Non-R01
1001 3 R01
1001 4 Non-R01
1001 5 R01
1001 6 R01
1002 1 R01
1002 2 Non-R01
1003 1 Non-R01
1003 2 R01
1004 1 Non-R01
1005 1 R01
If the RtnType field has a R01 value, then the Rtn_Int field should activate the count.
If the RtnType field has a Non-R01 value, then the Rtn_Int field should stop the count and reset to zero
and restart the count for the respective account number when the next R01 value appears in the subsequent record(s).
This should be the layout of the output file:
AccountNumber PmtNumber RtnType Rtn_Int
1001 1 Non-R01 0
1001 2 Non-R01 0
1001 3 R01 1
1001 4 Non-R01 0
1001 5 R01 1
1001 6 R01 2
1002 1 R01 1
1002 2 Non-R01 0
1003 1 Non-R01 0
1003 2 R01 1
1004 1 Non-R01 0
1005 1 R01 1
This was the code I wrote but the counter continues the count and does not reset to zero in order to start a new count:
data rtns_list_final;
set rtns_list;
by accountnumber;
if first.accountnumber then _n=0;
_n+RtnType='R01';
rtn_int = ifn(RtnType='R01',_n,0);
run;
Any assistance would be greatly appreciated. Thanks.
This appears to work for the provided example.
data want; set have; by accountnumber; if first.accountnumber then _n=0; if RtnType='Non-R01' then _n =0; else _n +1; run;
It seems like you need to replace
if first.accountnumber then _n=0;
with
if first.accountnumber or RtnType='R01' then _n=0;
This appears to work for the provided example.
data want; set have; by accountnumber; if first.accountnumber then _n=0; if RtnType='Non-R01' then _n =0; else _n +1; run;
@greg6363 wrote:
The code didn't work for me. You left out the rtn_int field.
If you can't figure out that the _n is the rtn_int field I predict a long hard road learning any programming.
My apologies, ballardw. I had a brain fart. I mistakenly copied a drop statement which removed the column which is why I didn't see it in my output. I'm looking at the column and the values are correct for the condition. I can use a rename statement to label the column. Thanks for setting me straight. Much appreciated.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.