BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
jz127323
Obsidian | Level 7
Hi, I have the following data step. But I find that the ID (_n_) is always equal to 1. 
Should it be 1, 2, ...10?
Thanks!



data Easyway; do Group='Placebo', 'Active'; do Subj=1 to 5; ID = _n_; input Score @; output; end; end; datalines; 250 222 230 210 199 166 183 123 129 234 ; run;

 

1 ACCEPTED SOLUTION

Accepted Solutions
ballardw
Super User

Incomplete data step will not run, no DATA at the top

 

The _n_ variable indicates how many times the data step executes, i.e. hits the bottom of the code and starts over.

Where you are using _n_ is in a loop. So the value that it has at the start of the DO loop stays the same until the loop finishes and then hits the second end.

 

If I understand what you want try this:

data example;
   do Group='Placebo', 'Active';
		do Subj=1 to 5;
		    ID+1;
			input Score @; 
			output; 			
		end;
	end;
datalines;
250 222 230 210 199
166 183 123 129 234
;
run;

The statement ID+1 implies the ID value is retained across iterations of the data step and each time the statement is encountered in the loop 1 is added.

 

 

View solution in original post

2 REPLIES 2
Tom
Super User Tom
Super User

Why would _N_ change?  You didn't do anything to make it change.  Like assigning it a value.  Or starting the next iteration of the data step, which is what normally makes _N_ increment.

 

What is the difference between SUBJ and ID in your dataset?

If you want ID to be 1 when GROUP is 'Placebo' and 2 then it is 'Active' then set its value inside the outer DO loop.

do Group='Placebo', 'Active';
   ID+1;
   do SUBJ=1 to 5;
   ...
ballardw
Super User

Incomplete data step will not run, no DATA at the top

 

The _n_ variable indicates how many times the data step executes, i.e. hits the bottom of the code and starts over.

Where you are using _n_ is in a loop. So the value that it has at the start of the DO loop stays the same until the loop finishes and then hits the second end.

 

If I understand what you want try this:

data example;
   do Group='Placebo', 'Active';
		do Subj=1 to 5;
		    ID+1;
			input Score @; 
			output; 			
		end;
	end;
datalines;
250 222 230 210 199
166 183 123 129 234
;
run;

The statement ID+1 implies the ID value is retained across iterations of the data step and each time the statement is encountered in the loop 1 is added.

 

 

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

SAS Training: Just a Click Away

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

Browse our catalog!

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