BookmarkSubscribeRSS Feed
nishSAS
Calcite | Level 5

Hello,

 

I am trying to create edit existing variable values with the help of DO LOOP in SAS Data Step. Below is the code i have written for the same. But when i am running this code I am not getting the expected result. What is going wrong in my code can you please suggest the corrections

 

data IN;
set IN;
  do x = 1 to 20;/*Update the Range if fill Number Value goes beyond 20*/
       y = x - 1;
if fill_Number = x then fill_Number = y;
else fill_Number = x;
end;
run;

 

Please correct me if my code is wrong.

 

Thanks

5 REPLIES 5
PeterClemmensen
Tourmaline | Level 20

What goes wrong? What do you expect and what results do you get?

Kurt_Bremser
Super User
data out;
/* it is never a good idea to overwrite the incoming dataset */
/* if something bad happens, all work up to now is lost */
set in;
do x = 1 to 20;/*Update the Range if fill Number Value goes beyond 20*/
  y = x - 1;
  if fill_Number = x
  then fill_Number = y;
  else fill_Number = x;
end;
run;

The way your code is written, fill_number will ALWAYS end up as 20.

nishSAS
Calcite | Level 5

Thanks Kurt

 

Kurt_Bremser
Super User

That means

fillnumber = fillnumber - 1;

?

 

For further help, post example data in a data step with datalines, and the expected output. See my footnotes for advice.

RW9
Diamond | Level 26 RW9
Diamond | Level 26

Post test data in the form of a datastep so we can see the inputs.  Show what output should be from that data.  We cannot guess from nothing.  

Generally a do loop iterates only within the individual observations, so in this case, for each observation the do loop will run 20 times, setting y to loop iteration -1, and when that equals x then the variable fill_number becomes the value in y, otherwise fill_number becomes x.  So from that logic you can see that the logic is never going to be right.  Take an example:

loop 1: fill_number=0, x=1, y=x-1=0, fill_number set to 0

loop 2: fill_number=0, x=2, y=x-1=1, fill_number set to 2

loop 3: fill_number=2, x=3, y=x-1=2, fill_number set to 2

loop 4: fill_number=2, x=4, y=x-1=3, fill_number set to 3

...

 

As I can't see what you wanted to achieve i can't tell if that is right or "not working".

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 5 replies
  • 901 views
  • 0 likes
  • 4 in conversation