## do loop sum in data step

Regular Contributor
Posts: 154

# do loop sum in data step

Hi,

My input data c1 is as following:

Date            | P1   | P2   |  Mean

-----------------------------------------

01JUN2017 | 200 | 300 |   3.2

-----------------------------------------

02JUN2017 | 230 | 320 |   2.7

-----------------------------------------

03JUN2017 | 250 | 340 |   3.7

-----------------------------------------

For each row, I would like to calculate Q_1, which based on the following function (pseudo code):

Do i = 1 to 10:

Q_1 =  sum(P1 * pdf('Poisson', 1, Mean) * max((i-1),0) + P2 * pdf('Poisson', 1, Mean) * max((1-i),0))

so that output table c2 will have another column called 'Q_1' for each date.

My initial code:

Data c2;

Set c1;

do i = 1 to 10;

Q_1 =  sum(P1 * pdf('Poisson', 1, Mean) * max((i-1),0) + P2 * pdf('Poisson', 1, Mean) * max((1-i),0));

output;

end;

drop i;

Run;

But it returns 10 values of 'Q_1' for each date. How could I write it in data step?

Thank you!

Super User
Posts: 13,338

## Re: do loop sum in data step

It would really really help to have some more actual example input data and the result of hand calculations for that data. As a datastep.

I am not going to write code to read data with dashed lines in the middle.

As it is we now have to ask "why 10?".

This bit:

max((1-i),0));

will return 0 for every value of i = 1 to 10 because 1-1=0, 1-2 =-1 <0, 1-3=-2 < 0 1-10= -9.

so I kind of expect you to get many values of 0. I do not see how you could get any any value of 'Q_1'

If you expected to get 10 values for each date then perhaps an ARRAY of Q:

Regular Contributor
Posts: 154

## Re: do loop sum in data step

Hi ballardw,

As I used max function, for example 'max((1-i), 0)'. It will only return 0 for i = 1

But I did get 10 values of 'Q_1' for each Date. Maybe because I set i =1 to 10?

Thank you!

Super User
Posts: 13,338

## Re: do loop sum in data step

You haven't shown any data for the output but if you notice that you have an Output statement between Do i = 1 to 10 and the End, then the Output gets exectuted for each trip through the loop.If you don't want that behavior then remove the output. The you only get the output at the end of the loop.

If you expect 10 distinct values then you need 10 variables instead of Q_1.

Perhaps

Array q_ {10};

do i = 1 to 10;

Q_[i] =  sum(P1 * pdf('Poisson', 1, Mean) * max((i-1),0) + P2 * pdf('Poisson', 1, Mean) * max((1-i),0));

end;

Regular Contributor
Posts: 154

## Re: do loop sum in data step

Thanks ballardw,

I just removed 'output' in the data step as you suggested, and it returned one value for each date.

This is what I need. Thanks!

Discussion stats
• 4 replies
• 364 views
• 1 like
• 2 in conversation