Again, i want to emphasize i come from spss and i'm very new to sas. I'm looking for sas equivalents.
Here's some spss code.
vector xvec=x1 to x10. * same as array xvec{10} x1-x10;
loop i=1 to 10; * same as do i=1 to 10;
do if (z eq 12).
compute x(i)=x(i)+2.
else if (z eq 15).
compute x(i)=x(i)+5.
else.
compute x(i)=x(i)+15.
end if.
end loop.
An alternative (with a variation) would-could be
vector xvec=x1 to x10.
do if (z eq 12).
loop i=1 to 10;
compute x(i)=x(i)+2.
end loop.
else if (z eq 15).
loop i=1 to 10;
compute x(i)=x(i)+15.
end loop.
else.
compute w=x1*x3.
end if.
end loop.
I know (courtesy of Ron Cody's book) that sas has a if-else if structure but my (very limited) understanding is that if-else if can't interact with a do-end structure because the if-else if must have a 'then' result.
I assume sas can do this; but how?
Thanks, Gene Maguin
PS. I'm interested in suggestions of sas books that build on Ron's book.
I don't know SPSS syntax but your code looks like
array x{10};
do i = 1 to dim(x);
if z = 12 then x{i} = x{i} + 2;
else if z = 15 then x{i} = x{i} + 5;
else x{i} = x{i} + 15;
end;
If I remember the SPSS correctly then
vector xvec=x1 to x10.
do if (z eq 12).
loop i=1 to 10;
compute x(i)=x(i)+2.
end loop.
else if (z eq 15).
loop i=1 to 10;
compute x(i)=x(i)+15.
end loop.
else.
compute w=x1*x3.
end if.
end loop.
would be:
array x{10};
if z = 12 then do i = 1 to dim(x);
x{i} = x{i} + 2;
end;
else if z = 15 then do i = 1 to dim(x);
x{i} = x{i} + 5;
end;
else w=x1*x3;
You could use the same approach that @PGStats with the W=x1*x3 calculation instead of the x{I}=x{I}+15 , it would just be done 10 times with identical results.
Or
select (z);
when (12) do i = 1 to dim(x);
x{i} = x{i} + 2;
end;
when (15) do i = 1 to dim(x);
x{i} = x{i} + 5;
end;
otherwise w=x1*x3;
end;
The select statement/when/block becomes more attractive when there are more than 2 or 3 "elses" involved.
And sometimes you get semi-slick values and
if z in (12 15) then do i= 1 to dim(x); x[i] = x[i] + (z-10); end; else w=x1*x3;
loop i=1 to 10; * same as do i=1 to 10;
do if (z eq 12).
compute x(i)=x(i)+2.
else if (z eq 15).
compute x(i)=x(i)+5.
else.
compute x(i)=x(i)+15.
end if.
end loop.
Another way::
do I= 1 to dim(X); X[I] = X[I] + 2*(Z=12) + 5*(Z=15) + 15*(Z ^in (12 15)); end;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.