## Do while issue

Solved
Occasional Contributor
Posts: 11

# Do while issue

HI all,

I have the following code with Do while loop:

DATA test1;

set test;

GR3SUM=0;

do while(GR3 = 1);

GR3SUM+1;

output;

end;

RUN;

The run is an infinite loop. How should I revise it?

Test file has the following data:

NID GR3

8 0

8 0

8 1

8 1

8 1

8 0

8 1

8 1

8 0

Thanks,

York

Accepted Solutions
Solution
‎07-01-2014 10:03 AM
Super User
Posts: 6,778

## Re: Do while issue

Sounds like this should work:

data test1;

set test;

if gr3=0 then gr3sum=0;

else gr3sum + gr3;

run;

If you might have missing values for gr3, you have to think about the right way to handle that.

Good luck.

All Replies
Super User
Posts: 23,740

## Re: Do while issue

You use GR3 as the loop stopping point but GR3SUM as the variable. Change one or the other, but they should be the same.

DATA test1;

set test;

GR3SUM=0;

do while(GR3SUM = 1);

GR3SUM+1;

output;

end;

RUN;

Posts: 1,270

## Re: Do while issue

If trying to get sum of GR3 variable then try this.

DATA test1;

set test end=eof;

GR3SUM+GR3;

if eof then  output;

RUN;

Super User
Posts: 23,740

## Re: Do while issue

What do you want the output to be?

Occasional Contributor
Posts: 11

## Re: Do while issue

Hi,

In this code, I would like to have another column of GR3SUM generated with each value would be the sum of the values of GR3. So the purpose is not to get a single value of the sum of GR3.

The ultimate goal I would like to achieve is to have the GR3SUM values to be the sum of the values of GR3 when consecutive GR3 is 1; whereas GR3SUM to be 0 when GR3 is 0. So the current code is just like preliminary step for test purpose.

Thanks,

York

Solution
‎07-01-2014 10:03 AM
Super User
Posts: 6,778

## Re: Do while issue

Sounds like this should work:

data test1;

set test;

if gr3=0 then gr3sum=0;

else gr3sum + gr3;

run;

If you might have missing values for gr3, you have to think about the right way to handle that.

Good luck.

Occasional Contributor
Posts: 11

## Re: Do while issue

Great. Thanks, It works.

York

Occasional Contributor
Posts: 11

## Re: Do while issue

I have another followup question. What if I have a data set with 1000 subjects, e.g., NID has 1 to 1000?  How could I do the same analysis for each subject?

Thanks,

York

Super User
Posts: 6,778

## Re: Do while issue

Sure, not much revision needed.  Your incoming data set would have to be sorted by SUBJECT.  Then:

data test1;

set test;

by subject;

if first.subject then gr3sum=0;

if gr3=0 then gr3sum=0;

else gr3sum + gr3;

run;

Super User
Posts: 6,778

## Re: Do while issue

Perhaps this is what you are looking for:

data test1;

set test;

if gr3=1 then gr3sum + 1;

run;

But I agree with Reeza.  It's not clear what you are trying to achieve.

🔒 This topic is solved and locked.