## DOW loop

Super Contributor
Posts: 464

# DOW loop

hi guys,

if i want to find the total sum of all the by groups do i create another data set to find it or can i do it within this code below?

so far the code below computes the sum of score2 within each by group.But i also want to find the total sum of score2

Thanks

data a;

input status \$ score1 score2;

cards;

medium 23 33

high 33 44

low 12 22

low 11 44

high 10 20

medium 33 66

medium . 44

;

proc sort;by status;

run;

data b;

do until(last.status);

set a;

by status;

sum=sum(sum,score2);

end;

proc print;run;

Super User
Posts: 23,700

## Re: DOW loop

proc means does it by default...

proc means data=a  sum;

ways 0 1;

class status;

output out=summary1 sum(score2)=sum;

run;

Super User
Posts: 10,778

## Re: DOW loop

Why not add another variable ?

data b;

retain total ;

do until(last.status);

set a;

by status;

sum=sum(sum,score2);

total=sum(total,score2);

end;

Super User
Posts: 8,092

## Re: DOW loop

Do you want the total for all of the BY groups?

If you want to stick with the DOW theme then add another one that loops over the whole dataset once and retains the value onto the rest of the observations you are generating.

data b;

if _n_=1 then do until (eof);

set a end=eof;

total+score2;

end;

do until(last.status);

set a;

by status;

sum=sum(sum,score2);

end;

run;

Super Contributor
Posts: 464

## Re: DOW loop

Tom,

if i only use the below part of your code :

data b;

if _n_=1 then do until (eof);

set a end=eof;

total+score2;

end;

proc print;run;

i'd get this output:

Obs    status    score1    score2    total

1     medium       .        44       273
2     medium       .        44       273

So my question is why do i get the observation twice,why not once only?

Posts: 5,526

## Re: DOW loop

This has to do with the way SAS detects the end of a datastep execution. If you only want to scan the whole dataset, use this instead :

data b;

do until (eof);

set a end=eof;

total + score2;

end;

proc print;run;

PG
Super User
Posts: 8,092

## Re: DOW loop

This note in your log is clue as to what is happening:

NOTE: DATA STEP stopped due to looping.

SAS does not normally stop at the end of the data step. Normally it stops when you read past the end of file with in INPUT or SET/MERGE/UPDATE command. Since it can never read past the end of the file because of IF and DO conditions it runs through the data step twice before it notices on the second time that you did not input anything and stops the step.

Posts: 5,526

## Re: DOW loop

Thank you Tom for explaining (again) that feature of the datastep. I can never remember the finer details of how this works... - PG

PG
Super Contributor
Posts: 464

## Re: DOW loop

Thanks Tom and PGStats.Interesting thing.Never knew this capability if data-steps.

Super Contributor
Posts: 464

## Re: DOW loop

Thanks guys!

Discussion stats
• 9 replies
• 283 views
• 5 likes
• 5 in conversation