Qbik
Qbik

Reputation: 6147

How to iterate simoultaneusly throught two sets in SAS?

I've tried something like this :

data wynik;
set dane;
if x>3 than x3=3*x;
else set dane2; x3=x2;set dane;
run;

dane and dane2 have the same number of rows

result is interesting - condition x>3 is still holding after setting dane2, but SAS always takes first observation - that is, it doesn't pass the current state of hidden loop counter. Make question is - does SAS have/use hidden loop with counter while iterating through dataset which could be accessed by user ?

editon : mayby I should add in title - without expicit loops, but this would also be welcomed

Upvotes: 1

Views: 166

Answers (1)

Joe
Joe

Reputation: 63424

Making some assumptions:

data dane;
do x = 1 to 5;
output;
end;
run;

data dane2;
do x2 = 5 to 1 by -1;
output;
end;
run;

data wynik;
merge dane dane2;
if x > 3 then x3=3*x;
else x3=x2;
put x3=;
run;

That uses the side-by-side merge (merge with no by statement) to get you both values at once.

To answer your followup question:

does SAS have/use hidden loop with counter while iterating through dataset which could be accessed by user ?

Yes, it does; _n_ defines the current loop iteration (as long as it isn't modified externally, which it can be - it is just a regular variable that's not written out to the dataset). So you could similarly do the following:

data wynik;
set dane;
if x > 3 then x3=x*3;
else do;
  set dane2 point=_n_;
  x3=x2;
end;
put x3=;
run;

The side-by-side merge is preferred because it will be faster, unless you very infrequently need to look at DANE2. It's also easier to code.

Upvotes: 3

Related Questions