mardi 2 octobre 2018

How did SAS iteration works via variable _N_ and if else

I have encouterd this following code which works quiet not intuiative, as SAS should process step by step. However, following code seems to somehow jumps back to the previous code like a loop.

See the difference of flag and pageit in reset and reset_p2.

Generate dataset:

data new;
  do i=1 to 100;
    if i < 72 then type='first';
    else type='last';
    newval='newval'||left(i);
    output;
  end;
run;

The mystery code:

data reset;
  set new;
  by type;
  if _n_ eq 1 then flag=0;   
  else flag+1;
  if flag>=25 then do;
    pageit+1; 
    flag=0;
  end;
run;

an attempt to understand this code: we seperate the step

data reset_p1;
  set new;
  by type;
  if _n_ eq 1 then flag=0;   
  else flag+1;
run;

data reset_p2;
  set reset_p1;
  if flag>=25 then do;
    pageit+1; 
    flag=0;
  end;
run;

The pageit and flag column are different in reset and reset_p2.

pageit and flag in reset:

enter image description here

pageit and flag in reset_p2:

enter image description here

This means the code seems to not run step by step, but somehow jumps back to "if n eq 1" part. Anyone can explain why could this happen ? As this is really not intuitative.

Aucun commentaire:

Enregistrer un commentaire