Dear SAS Experts,
I am trying to sum a series using a do loop but I cannot seem to figure out how to do that as I am getting errors in all my attempts.
here is what tried and failed:
do while(n<addyrs);
do t = 6 to (n+6);
sum = 0;
sum = EMLP/((1+K)**t);
end;
end;
when I run this code I get the following error:
Thanks!
Hello @AmirSari,
Simplify your code and use a single DO loop:
data want(drop=t);
K=0.02; EMLP=17; Addyrs=42; /* replace with your values */
do t=6 to 6+Addyrs;
sum + EMLP/((1+K)**t);
end;
run;
Or use the formula for the geometric sum, then you don't need a loop at all:
data want(drop=q);
K=0.02; EMLP=17; Addyrs=42; /* replace with your values */
q=1/(1+K);
sum=EMLP*q**6*(1-q**(Addyrs+1))/(1-q);
run;
Hello,
Can you show a complete runnable code ?
Here, you will have an infinite loop as n is not modified inside the loop.
The error message can result from variables in the do statements having missing values.
Also, in your code, sum is reinitialized at each step.
I think you meant :
sum=0; n=0;
do while(n<addyrs);
do t = 6 to (n+6);
sum + EMLP/((1+K)**t);
end;
n+1;
end;
Edit : added an n increment to avoid an infinite loop but it might not be what you need.
Hello @AmirSari,
Simplify your code and use a single DO loop:
data want(drop=t);
K=0.02; EMLP=17; Addyrs=42; /* replace with your values */
do t=6 to 6+Addyrs;
sum + EMLP/((1+K)**t);
end;
run;
Or use the formula for the geometric sum, then you don't need a loop at all:
data want(drop=q);
K=0.02; EMLP=17; Addyrs=42; /* replace with your values */
q=1/(1+K);
sum=EMLP*q**6*(1-q**(Addyrs+1))/(1-q);
run;
It is almost never a waste of time to provide a small example data set, especially in the form of data step code, of the start and the desired result.
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.