Can anyone explain to me the logic behind these 2 codes please (uses set in loop):
Code 1:
Data class1 ;
Do I=1 to 2 ;
Set sashelp.class;
End;
Run;
proc print; run;
Code 2:
Data class1 ;
Do I=1 to 3 ;
Set sashelp.class;
End;
Run;
proc print; run;
Output code 1:
Output code 2:
You could take code Data class1 ; Do I=1 to 2 ; Set sashelp.class; End; Run; As this Data class1 ; Do I=1 to 2 ; Set sashelp.class; End; output; /*<--*/ Run; Therefore, it would output the 2nd,4th,6th,8th,10th,12th..... obs.
One way to explore this is to add PUT statements, showing the value of _N_ and other variables.
For example, try running:
data class1 ;
do i=1 to 2 ;
set sashelp.class;
put "Inside Loop" (_N_ i Name)(=) ;
end;
put "Outside Loop" (_N_ i Name)(=) ;
run;
Since you read 2 (or 3) observations but output one it seems pretty obvious what it is doing.
Notice how the 3rd observation in the first run matches the 2nd observation in the second run. Confirming the mathematical equality that 2*3 is the same as 3*2.
If you are trying to examine the behavior of multiple Set statements I recommend using multiple small data sets of different sizes, small number of variables, some with different names and (at least some) values unique to the data set.
That way have some chance of possibly seeing which actual set contributed which record. Plus you may get an education of what happens with sets and different numbers of observations.
If the question is about the value of I
@vijaypratap0195 wrote:
Can anyone explain to me the logic behind these 2 codes please (uses set in loop):
I'm not entirely sure of what you are asking, but ...
In general, using SETs inside a DO loop is done for purposes of aggregating a series of obs, often a having a single ID. Once the aggregation calculations are done, often a second use of SET within a DO loop is done to reread (and explicitly OUTPUT) the same obs, but with additional group-related information.
You could take code Data class1 ; Do I=1 to 2 ; Set sashelp.class; End; Run; As this Data class1 ; Do I=1 to 2 ; Set sashelp.class; End; output; /*<--*/ Run; Therefore, it would output the 2nd,4th,6th,8th,10th,12th..... obs.
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.
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.