DATA Step, Macro, Functions and more

Retaining Values in a Do Loop

Accepted Solution Solved
Reply
Super Contributor
Posts: 297
Accepted Solution

Retaining Values in a Do Loop

Hi Guys,

I am sure there is a very good reason for this, but I can't seem to get it through my thick head at 2am.

Why, when I run the below code, am I retaining the value of the previous OBS when I concatenate using the 3 arguments below?

DATA ENROLLMENT;

ATTRIB GROUP_ID LENGTH = $400;

DO ID = 1 TO 10;

  DO J = 1 TO 1;

  GROUP_ID = CATS(GROUP_ID,ID,"P");

  END;

  OUTPUT;

END;

RUN;

It is driving me nuts.  Sorry to ask such a newbie question.

Regards,

Scott


Accepted Solutions
Solution
‎06-02-2014 06:17 AM
Super User
Posts: 7,781

Re: Retaining Values in a Do Loop

Posted in reply to Scott_Mitchell

The data step variables are set to missing only when the complete data step enters its next iteration (think of the jump from "run" to "data"). Between "data" and "run" (or whatever begins the next SAS program step) the variables keep their values, no matter how many SET or OUTPUT statements you have.

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers

View solution in original post


All Replies
Solution
‎06-02-2014 06:17 AM
Super User
Posts: 7,781

Re: Retaining Values in a Do Loop

Posted in reply to Scott_Mitchell

The data step variables are set to missing only when the complete data step enters its next iteration (think of the jump from "run" to "data"). Between "data" and "run" (or whatever begins the next SAS program step) the variables keep their values, no matter how many SET or OUTPUT statements you have.

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
Super Contributor
Posts: 297

Re: Retaining Values in a Do Loop

Posted in reply to KurtBremser

Thanks everyone.

Super User
Super User
Posts: 7,950

Re: Retaining Values in a Do Loop

Posted in reply to Scott_Mitchell

Yep, it looks like the last value is being held over in memory after the output statement.  Pop a clean statement in after the output, would need to check the documentation as to exactly what it is doing:

DATA ENROLLMENT;

ATTRIB GROUP_ID LENGTH = $400;

DO ID = 1 TO 10;

  DO J = 1 TO 1;

    GROUP_ID = CATs(GROUP_ID,ID,"P");

    output;

    group_id="";

  END;

END;

RUN;

Regular Contributor
Posts: 151

Re: Retaining Values in a Do Loop

Posted in reply to Scott_Mitchell

I believe you can also get around this by using the CALL CATS function.

DATA ENROLLMENT;

ATTRIB GROUP_ID LENGTH = $400;

DO ID = 1 TO 10;

  DO J = 1 TO 1;

  CALL CATS(GROUP_ID,ID,"P");

  END;

  OUTPUT;

END;

RUN;

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 315 views
  • 7 likes
  • 4 in conversation