BookmarkSubscribeRSS Feed
stat34986
Calcite | Level 5

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.

 

StudentClass1Class2Class3Class4Class5
1     
2     
3     
4     
5     
6     
7     
8     
9     
10     
11     
12     
13     
14     
15     
16     
17     
18     
19     
20     
2 REPLIES 2
PaigeMiller
Diamond | Level 26

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.

--
Paige Miller
ballardw
Super User

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;

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 695 views
  • 2 likes
  • 3 in conversation