BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
rick_b
Fluorite | Level 6

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)

 

 

1 ACCEPTED SOLUTION

Accepted Solutions
FreelanceReinh
Jade | Level 19

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.

View solution in original post

5 REPLIES 5
Kurt_Bremser
Super User
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;
rick_b
Fluorite | Level 6
Thanks, Kurt.
FreelanceReinh
Jade | Level 19

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.

rick_b
Fluorite | Level 6
Thank you!

sas-innovate-white.png

Register Today!

Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.

Register now!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 5 replies
  • 901 views
  • 0 likes
  • 4 in conversation