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,
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.