Does anyone have a nice solution on how to multiply every first position with 2 and every second position with 1?
Please see example below.
%macro Check;
data Check;
set sashelp.Margarin (keep= HouseID);
HouseIDtxt=put(HouseId,7.0);
%do i= 1 %to 7;
HousIDPosition&i=substr(HouseIDtxt,&i,1);
%end;
run;
%mend Check;
%Check
Every time &i
is odd I want HousIDPosition&i
to be multiplied by 2 and every time &i
is even I want it multiplied by 1.
Use the Mod Function in %Sysfunc. See if you can use this as a template.
%macro m;
%do i = 1 %to 10;
%if %sysfunc(mod(&i, 2)) = 0 %then %put &i. is even!;
%else %put &i. is odd!;
%end;
%mend;
%m
Use the Mod Function in %Sysfunc. See if you can use this as a template.
%macro m;
%do i = 1 %to 10;
%if %sysfunc(mod(&i, 2)) = 0 %then %put &i. is even!;
%else %put &i. is odd!;
%end;
%mend;
%m
Btw, here is my final code:
%macro Check;
data Check;
set sashelp.Margarin (keep= HouseID);
HouseIDtxt=put(HouseId,7.0);
%do i= 1 %to 7;
%if %sysfunc(mod(&i, 2)) = 0 %then %do;
HousIDPositionMult&i= substr(HouseIDtxt,&i,1)*1;
%end;
%else %do;
HousIDPositionMult&i= substr(HouseIDtxt,&i,1)*2;
%end;
%end;
run;
%mend Check;
%Check
Instead of a macro you could use an array in the data step:
data check(drop=i);
set sashelp.Margarin(keep=HouseID);
array HousIDPositionMult[7];
do i=1 to 7;
HousIDPositionMult[i]=mod(int(HouseID/10**(7-i)),10)*(mod(i,2)+1);
end;
run;
This would also avoid the unwanted notes "Character values have been converted to numeric values ..." in the log as it multiplies numbers, not character strings.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.