DATA Step, Macro, Functions and more

Nested Loop problem

Reply
Frequent Contributor
Posts: 85

Nested Loop problem

Hi,

My basic question is to produce dataset based on 3 loops from our central repository. My desired output should be like this

Id1Id2Id3Id4




11100I1


200I2


300I3


400I4


500I5


600I6
221100I7


1200I8


1300I9


1400I10


1500I11


1600I12
332100I13


2200I14


2300I15


2400I16


2500I17


2600I18

So I want to loop Id1 3 times thats my outermost loop, Id2 3 times thats my first inner loop and then Id3 and Id4 6 times each... I am able to produce output for Id1 but the only thing I M getting confused about is where to apply ends for inner loops and where to apply output statement... Guess my C background is making me confused... Any suggestions would be really  helpful

Super User
Posts: 10,500

Nested Loop problem

Your example doesn't show ld2 looping but rather the same as ld1. And ld4 doesn't actually look like a loop per se.

When you say you want to create a dataset do you actuall want the values of ld1 and ld2 to be blank or did you suppress them to show the loop structure?

Super User
Posts: 10,500

Re: Nested Loop problem

Assuming the blanks were for clarity but that the ld1 and ld2 variables are actually in the data this produces data as your example.

data junk (drop= count t);
   count=0;
   do ld1 = 1 to 3;
      ld2 = ld1;
      t= (ld2-1) * 1000;
      do ld3 = (t+100) to (t+600) by 100;
         count+1;
         ld4= cats('l',put(count,f2.0));

         output;
      end;
   end;
run;

Super User
Super User
Posts: 6,500

Re: Nested Loop problem

What you said you wanted looks like this.  Not sure that it is really much different than C or any other language.

do id1=1 to 3;

  do id2=1 to 3;

    do id3=1 to 6;

      do id4=1 to 6;

        output;

      end;

    end;

  end;

end;

What you produced as a table looks more like this.

do id1=1 to 3;

  id2=id1;

  do id3loop=1 to 6;

    id3=1000*(id1-1)+100*id3loop;

    rec+1;

    id4=cats('l',rec);

    output;

  end;

end;

Ask a Question
Discussion stats
  • 3 replies
  • 174 views
  • 0 likes
  • 3 in conversation