data temp; infile DATALINES dsd missover; input ID DATE(month_num) num_obs var1; CARDS; 01, 1, 5, . 01, 2, 5, 1 01, 3, 5, 1 01, 4, 5, 2 01, 5, 5, 2 02, 1, 4, . 02, 2, 4, 1 02, 3, 4, 2 02, 4, 4, 3 02, 5, 4, 4 ; run;
I'm trying to do a do-loop that varies in the last iteration, for each id, based on the value of 'num_obs' for that ID.
So I want something like
DO i = 1 to num_obs;
<bla bla bla>
END;
So that my DO loop evaluates from i = 1 to 5 for ID = 1,
then from i = 1 to 4 for ID = 2.
Is this possible?
I also need to use this in a macro, because for each loop, I'll be using i has a macro variable like so:
%DO i = 1 %to num_obs;
IF lag&i(var) = bla bla bla;
%END;
Is this possible?
Thanks
You can definitely do a do-loop that varies in the last iteration, for each id, according to a variable.
Please have a look at the following result -> I have not dropped i so that you can see the number of iterations ->ex, for ID=01, numobs = 5, i looped from 1 to 5. When i=6, the do loop stops as 6 > numobs.
data want;
set temp;
do i = 1 to num_obs;
end;
run;
proc print;
Regarding your second question, you cannot write this %DO i = 1 %TO numobs;
-> numobs should be a macrovariable.
Could you please give some more details about what you're going to achieve?
NB: another thing is that using the LAG function in an IF statement is not recommended at all, leading to unexpected results. You should fix the lagged values in a variables before using them in a conditional statement.
Best,
What is your desired result here?
You can definitely do a do-loop that varies in the last iteration, for each id, according to a variable.
Please have a look at the following result -> I have not dropped i so that you can see the number of iterations ->ex, for ID=01, numobs = 5, i looped from 1 to 5. When i=6, the do loop stops as 6 > numobs.
data want;
set temp;
do i = 1 to num_obs;
end;
run;
proc print;
Regarding your second question, you cannot write this %DO i = 1 %TO numobs;
-> numobs should be a macrovariable.
Could you please give some more details about what you're going to achieve?
NB: another thing is that using the LAG function in an IF statement is not recommended at all, leading to unexpected results. You should fix the lagged values in a variables before using them in a conditional statement.
Best,
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.