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;
Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.
Register today!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.
Select SAS Training centers are offering in-person courses. View upcoming courses for: