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;

Ready to join fellow brilliant minds for the SAS Hackathon?

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

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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