> Hi, I have a very simple issue to do but I can't work
> it out. I have a subject ID column and I want to add
> a variable (counter) telling me the number of times
> the ID is repeated or not.
> I tried to do a loop like this:
>
> do i= 1 to 28872;
> if ID(i) = ID(i-1) then counter=1;
> else counter=0;
> run;
Maneco -
Ah, I've made this mistake before. You can't think of SAS datasets as being like arrays -- you can't access each record (row) in a SAS dataset by its observation number. You're thinking like a "normal" programmer rather than like a SAS programmer.
This does what I think you're looking for:
data check;
set have;
checkrepeat=(ID=priorid); * 1 if ID is same as prior value, 0 if not;
PriorID=ID; * creates a new variable to hold the value of ID;
retain PriorID; * keeps PriorID at its _old_ value so you can check it against
the new value of ID;
* if checkrepeat; * optionally restricts the new dataset to repeated values of ID;
run;
The keyword "retain" can be a bit tricky to get used to, but as you can see it does the job,
Oh, there's a simpler way using the lag() function:
data check;
set have;
checkrepeat=(id=lag(id)); * 1 if id is same as prior value, 0 if not;
* if checkrepeat; * optionally restricts the new dataset to repeated values of id;
run;
(I learned to use retain before I found lag(), so it comes more naturally to me. :>)
Cheers -
Kevin