I am trying to find a way to multiply a series of N variables. Each line has a different number of variables present. The first field is name and the second indicates the number of times that a multiplicative variable subsequently appears:
data my_data;
input name number_observations var1 var2 var3 var4 var5;
cards;
Ed 3 2 1 4 . .
Mary 5 2 1 2 3 5
Vince 1 3 . . . .
Mike 2 4 13 . . .
;
run;
Desired output:
Ed 3 2 1 4 . . 8 (e.g., 2*1*4)
Mary 5 2 1 2 3 5 60 (e.g., 2*1*2*3*5)
Vince 1 3 . . . . 3 (e.g., 3)
Mike 2 4 13 . . . 52 (e.g., 4*13)
Hello @rick_b,
Alternatively, you can apply the RESOLVE-%SYSEVALF trick to the variable list containing the factors:
options missing=' ';
data want;
set my_data;
if n(of var:) then prod=input(resolve('%sysevalf('||catx('*', of var:)||')'),32.);
run;
options missing='.';
(after correcting the DATA step reading the raw data).
Edit: Inserted the IF condition to catch the trivial all-missing case.
Also note the limitation of this technique (if you have thousands of factors) that the CATX(...) expression must not exceed a length of 32767 characters.
data long;
set my_data;
array vars var:,
do i = 1 to dim(vars);
if vars{i} ne .
then do;
value = vars{i};
output;
end;
end;
keep name value;
run;
data want;
set long;
by name;
if first.name
then product = value;
else product = product * value;
if last.name;
keep name product;
run;
Hello @rick_b,
Alternatively, you can apply the RESOLVE-%SYSEVALF trick to the variable list containing the factors:
options missing=' ';
data want;
set my_data;
if n(of var:) then prod=input(resolve('%sysevalf('||catx('*', of var:)||')'),32.);
run;
options missing='.';
(after correcting the DATA step reading the raw data).
Edit: Inserted the IF condition to catch the trivial all-missing case.
Also note the limitation of this technique (if you have thousands of factors) that the CATX(...) expression must not exceed a length of 32767 characters.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.