BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
meckarthik
Quartz | Level 8

Hi Guys,

Need help on do loop.

 

Got a scenario where the values are assigned between 1 to 1000 for each id, if the previous/last value assigned was 855  and if I want to have 2 incremental then, need to assign 856,857 etc (incrementally). Similarly, if the last value assigned was 998 and want to have 4 increments then need to assign as 999,1000, then go back to 1,2 etc.

 

 

How do i dealt this situation 

 

Any help! 

 

Karthik

1 ACCEPTED SOLUTION

Accepted Solutions
FreelanceReinh
Jade | Level 19

Hi @meckarthik,

 

You can increment the values using the MOD function:

v=mod(v,1000)+1;

Example:

data _null_;
v=998; /* start value */
n=4;   /* number of incrementations */
do i=1 to n;
  v=mod(v,1000)+1;
  put v=;
end;
run;

Result:

v=999
v=1000
v=1
v=2

 

View solution in original post

3 REPLIES 3
FreelanceReinh
Jade | Level 19

Hi @meckarthik,

 

You can increment the values using the MOD function:

v=mod(v,1000)+1;

Example:

data _null_;
v=998; /* start value */
n=4;   /* number of incrementations */
do i=1 to n;
  v=mod(v,1000)+1;
  put v=;
end;
run;

Result:

v=999
v=1000
v=1
v=2

 

meckarthik
Quartz | Level 8

Thank you so much. It was really helpful. Just one more to that, how do I create a temp table or insert to the table to capture all the 'v' 

FreelanceReinh
Jade | Level 19

Suppose you have

  1. a dataset HAVE with one observation per ID, containing ID and value (V),
  2. a dataset INCR with one observation per ID, containing ID and number of incrementations (N),

both sorted by ID.

 

Example:

data have(drop=n) incr(drop=v);
input id v n;
cards;
1 855 2
2 101 0
3 998 4
;

Then you can merge the two datasets by ID and in the same DATA step create the additional observations with the incremented V values for each ID:

data want(drop=n);
merge have incr;
by id;
output;
do n=1 to n;
  v=mod(v,1000)+1;
  output;
end;
run;

Result:

id       v

 1     855
 1     856
 1     857
 2     101
 3     998
 3     999
 3    1000
 3       1
 3       2

(Highlighted observations were newly inserted.)

 

If the number of incrementations (N) was already contained in dataset HAVE (rather than in a separate dataset), a simple

set have;

would replace the MERGE and BY statements and HAVE would not need to be sorted by ID.

 

To obtain a dataset consisting of the newly created observations alone, just delete the first of the two OUTPUT statements.