I would like to use the same if statement across different variables. I have 31 of these variables and would like to avoid typing multiple IF statements. Is there a more elegant way to achieve this? Here is my code:
data want;
set have;
%let ab = ab1-ab31;
if a1 = '0' and b1='0' then ab1='1';
else ab1='0';
if a2 = '0' and b2='0' then ab2='1';
else ab2='0';
if a3= '0' and b3='0' then ab3='1';
else ab3='0';
...
if a31 = '0' and b31='0' then ab31='1';
else ab31='0';
n_ab=sum((countc(cats(of &ab),'1')));
drop &ab;
run;
Since you're only interested in the sum of true conditions, this should do it:
data want;
set have;
n_ab = 0;
array a {*} a1-a31;
array b {*} b1-b31;
do i = 1 to 31;
n_ab = n_ab + (a{i} = "0" and b{i} = "0");
end;
drop i;
run;
Define arrays, and use an iterative DO loop.
Since you're only interested in the sum of true conditions, this should do it:
data want;
set have;
n_ab = 0;
array a {*} a1-a31;
array b {*} b1-b31;
do i = 1 to 31;
n_ab = n_ab + (a{i} = "0" and b{i} = "0");
end;
drop i;
run;
This may be a silly question to you but why are you creating so many character variables with values of '1' and '0' instead of numeric variables? Especially considering you are dropping them ?
My take assumes you don't already have AB variables so create numeric versions to SUM to get that count.
data want; set have; array a(*) a1-a31; array b(*) b1-b31; array ab(*) ab1-ab31; do i=1 to dim(a); ab[i]=( a[i]='0' and b[i]='0'); end; n_ab=sum(of ab(*)); drop i ab1-ab31 ; run;
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
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.