# Thread: Calculating winning/losing streaks

1. ## Calculating winning/losing streaks

Hi all,

just kind of a curious question about how best to program a variable that will determine a team's winning or losing streak.

So for example, let's there is data stored as follows:

Code:
``````proc format;
value result 1='win' 0='lose';
run;

data streak;
input game result;
format result result.;
cards;
1 1
2 1
3 0
4 1
5 1
6 0
7 0
8 1
9 1
10 1
;
run;``````
which records whether a team won or a lost a game (1=win, 0=lose). Now let's say I want to calculate a variable which records their winning or losing streak. So for example, in this instance the variable would look like:

Streak
1
2
-1
1
2
-1
-2
1
2
3

any suggestions on how to do this?

I feel as though I have a basic idea of what needs to happen (using a retain statement for the streak variable and then perhaps indicating that if the current result = the lag(result) then streak+1 or streak-1 otherwise it needs to do the opposite streak - for example switching from a winning to a losing streak or vice versa). However, I'm not quite sure how to best accomplish this.

Any help would be appreciated - it's more of a curiosity than anything.

2. ## Re: Calculating winning/losing streaks

Code:
``````data streak(drop=last);
set streak;
retain last streak;
if _N_=1 then do;
if result=1 then streak=1;
else streak=-1;
end;
else do;
if result=1 and last=1 then streak=streak+1;
else if result=1 and last=0 then streak=1;
else if result=0 and last=1 then streak=-1;
else streak=streak-1;
end;
last=result;
run;

proc print data=streak;
run;``````
I usually avoid lag function because at times the result could be unexpected. If the case is as simple as you've stated then for this case you can probably use the lag function.

3. ## The Following User Says Thank You to jrai For This Useful Post:

lancearmstrong1313 (11-05-2012)

4. ## Re: Calculating winning/losing streaks

Oh, so you literally just did a case by case basis (there are 4 possibilities and you have essentially 4 lines of code computing the streak)....makes sense.

I tried it on slightly more complicated data than what I presented and had to slightly modify it. I created a "previous winner" variable and used that variable instead of the "last" variable you created and it worked.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts