DATA Step, Macro, Functions and more

Problem with creating a counter variable

Occasional Contributor
Posts: 5

Problem with creating a counter variable

In my data set, I have a Month_Date field and a CustomerNo field.  I want to add a Counter field that starts from zero (0) for each Month_Date associated with a particular CustomerNo.  My macro defined a 36 month time frame but not all CustomerNo will have 36 observations.  Some might have 1 or 2 or 3 all the way up to 36.  This is how I want the output to appear:


MonthDate     CustomerNo     Counter

201410               288                  0

201411               288                  1

201412               288                  2

201501               288                  3

201502               288                  4

201410               351                  0

201411               351                  1

201412               351                  2


In this case, CustomerNo 288 has 5 observations and CustomerNo 351 has 3 observations.  The Counter should start from zero and end with the last given MonthDate for the respective CustomerNo. 


This is how I put together my code in a data step:


data Final;

set Master5;

by CustomerNo;

retain count;

label count='Counter";

keep MonthDate CustomerNo count;

if first.CustomerNo then 

count = 0;

else count = count + 1;



Unfortunately, the output for this code generates a counter (and outputs each MonthDate) for each of the 36 months set in my original macro, even if there is no MonthDate record in the data set for that particular CustomerNo. 


What am I doing wrong in this code?


Any assistance would be greatly appreciated.  Thanks.

Super User
Posts: 6,541

Re: Problem with creating a counter variable

[ Edited ]

Your DATA step is fine.  Check your MASTER5 data.  It looks like your "macro" (whatever you mean by that) accidentally created a data set with 36 observations for each customer.

Frequent Contributor
Posts: 113

Re: Problem with creating a counter variable

[ Edited ]

Try this....

data HAVE;
  do i=1 to 12;
   format date date9.;
drop i;

data WANT;
  HAVE (in=a obs=3)
  HAVE (in=b firstobs=2 obs=8)
  HAVE (in=c firstobs=7)
  HAVE (IN=d obs=1);

if b then custno=2;
if c then custno=3;
if d then custno=4;

proc sort;
  by custno date;

data WANT;
  set WANT;
  by custno;
if first.custno then counter=0;
  else counter+1;



Hope this helps.

Ask a Question
Discussion stats
  • 2 replies
  • 3 in conversation