I am trying to generate/create data in SAS that has the following form (see below) where class1-class5 variables will be filled with a random integer from 1-6. I am trying to do this with array and do loops via the following code
data classes; /* createa a dataset of students */
array class{5} class1-class5;
call streaminit(123);
do i = 1 to 20;
student=i;
do j=1 to dim(class);
class{j} = rand("INTEGER",1,6); /* class ~ U(1,6) */
output;
end;
end;
run;This does not work. I really don't understand why I am getting so many observations. I am finding do loops very counterintuitive in SAS compared to other programming languages.
| Student | Class1 | Class2 | Class3 | Class4 | Class5 |
| 1 | |||||
| 2 | |||||
| 3 | |||||
| 4 | |||||
| 5 | |||||
| 6 | |||||
| 7 | |||||
| 8 | |||||
| 9 | |||||
| 10 | |||||
| 11 | |||||
| 12 | |||||
| 13 | |||||
| 14 | |||||
| 15 | |||||
| 16 | |||||
| 17 | |||||
| 18 | |||||
| 19 | |||||
| 20 |
Your code works for me. You get 100 observations becuase the loop for i goes 1 to 20 and the loop for j goes 1 to 5 and within it there is an OUTPUT; statement, so 20*5 = 100.
Maybe you want this (I'm guessing because you didn't really say what you want) with the output statement outside of the j loop
data classes; /* createa a dataset of students */
array class{5} class1-class5;
call streaminit(123);
do i = 1 to 20;
student=i;
do j=1 to dim(class);
class{j} = rand("INTEGER",1,6); /* class ~ U(1,6) */
end;
output;
end;
run;
Now the output statement executes just 20 times.
The location of your OUTPUT statement inside the Do j= / end; loop means that the output executes for every value of J. Moving it after the end of the J= loop means that it only executes one time.
If you don't really need the variable i for some purpose you might also consider changing this
do i = 1 to 20;
student=i;
to
do student = 1 to 20;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
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.