Counting in Sas

Maybe a stupid question ... I got the following dataset:

id count x 1 y 2 z 3 a 1 b 2 c 3 etc. 

And I want this:

 id count group x 1 1 y 2 1 z 3 1 a 1 2 b 2 2 c 3 2 etc. 

Here is what I am trying:

 data macro_1; set vix.macro_spy; where macro=1; count+1; if count>3 then do; count=1; end; group=0; if count=1 then group+1; run; 

But it does not work. How can I add an entire β€œgroup” to one if I ever get β€œcount = 1”? Thanks.

+4
source share
2 answers

even easier

 data want; set vix.macro_spy; group+(count=1); run; 
+5
source

I'm not sure I understand what you need. So you ordered this data set so that the values ​​of the count variable always go 1, 2, 3, 1, 2, 3, 1, 2, 3... Now you want to generate the group variable so that the value increments every time the variable count goes through 3?

If so, you can do something like this:

 data group; set vix.macro_spy; retain group; if _N_ = 1 then group = 0; if count = 1 then group + 1; run; 

This is a common template that I use. The if _N_ = 1 is executed only once, here you initialize the variables.

Operator

retain ensures that the variable retains its value from one iteration of the DATA step to the next.

0
source

All Articles