Help using Base SAS procedures

Counting consecutive variable values

Occasional Contributor
Posts: 19

Counting consecutive variable values

[ Edited ]

Hello Fellow SAS Users, 


I have been working on something for a few weeks and just ran into a problem with my code. Esentially, I need SAS to count the number of consecutive variable values (including restarting values) separately for each participant. 


(I am not going to include my current SAS code, because I am sure it is very inefficient and there is a much better way to achieve this.)


I have two problems, but first take a look at an example of the output:

NAME = Participant

DSCD = Identifier

FYEAR = Year of observation

AUD = the variable for which I need to count the number of repititions 

TENURE = the count of the repition of AUD, as of the current FYEAR


output problem.png


My two problems are summarized as follows (based no the two red boxes): 

1. First, the very first observation for each participant should be where TENURE=1. My code is showing as TENURE=. and then starting TENURE=1 in the second observation. 


2. The more important problem is what happens in the second participant. The same problem as #1 above persists. But then in FYEAR=1996 for this participant, it is continuing off of the previous count string. 


Yet, interestingly, for both participants shown here (look at the BLUE boxes, FYEAR=2002 for the first and FYEAR=2007 for the second), when there is a change in the AUD variable, neither of the two preceding problems are present. The first year of the new AUD variable is = 1, and it restarts the count rather than pulling from the previous count. 


I would appreciate any help with this. Again, I'm sorry for not including my current SAS code but I am very confident that it is wasteful and inefficient. 

Occasional Contributor
Posts: 19

Re: HELP NEEDED ASAP: Counting consecutive variable values

Update: I am trying to create a simple DO loop and this is also giving me problems. Here's the code I'm working with for that: 


data tenure; set merged;
dscd1 = lag(dscd);
aud1 = lag(aud);

if dscd ne dscd1 then tenure=1; 
else if dscd=dscd1 then do;
if aud=aud1 then tenure = tenure1+1; 
if aud ne aud1 then tenure = 1; 

if tenure <=3 then tenure_c='S';
else if 7 >= tenure > 3 then tenure_c='M';
else if tenure > 7 then tenure_c='L';
else if tenure='.' then tenure_c='.';

Occasional Contributor
Posts: 19

Re: HELP NEEDED ASAP: Counting consecutive variable values

Figured it out, please do not reply.

Super User
Posts: 5,878

Re: HELP NEEDED ASAP: Counting consecutive variable values

First - nothing on this community can be ASAP. All entries are voluntary.

Second - if you figured out how to do it - share! Some om your peers can benefit from this. And it's nice to couple a solution to your question.

Data never sleeps
Ask a Question
Discussion stats
  • 3 replies
  • 2 in conversation