DATA Step, Macro, Functions and more

array and do loops

Reply
Frequent Contributor
Posts: 110

array and do loops

Hi SAS Users,

I have the following sample dataset with 3 variables: ID m_start and m_end where m_start and m_end correspond to months in a year (e.g. m_start =1 is January and m_end=12 is December; m_start=2 is February and m_end=5 is May).

data have;

ID m_start m_end

1   1          3

2   5          8

3   7          12  

I would like to create 12 new variables: new_m1-new_m12 that counts the months from m_start to m_end.  So my new dataset would resemble the below data set.

data want;

ID m_start m_end new_m1 new_m2 new_m3 new_m4 new_m5 new_m6 new_m7 new_m8 new_m9 new_m10 new_m11 new_m12;

1   1          3           1          1            1          .               .               .          .          .               .               .          .          .

2   5          12          .           .            .           .              1              1          1          1             1               1          1         1  

3   7          12         .            .           .            .               .               .          1          1             1               1          1          1

Thanks!

Super User
Posts: 19,822

Re: array and do loops

Posted in reply to sophia_SAS

Use the m_start and m_end as the start/end of your iteration in your do loop and create an empty array that you can fill in.

data want;

set have;

array new(12) new_m1-new_m12;

do i=m_start to m_end;

new(i)=1;

end;

run;

Frequent Contributor
Posts: 110

Re: array and do loops

Thanks Reeza.  That worked.

Ask a Question
Discussion stats
  • 2 replies
  • 212 views
  • 0 likes
  • 2 in conversation