I have a few variables that have values specified.
%let a_val=20;
%let b_val=30;
%let c_val=40;
I also have a data set that looks like this.
data have;
input name $ a b c;
cards;
joe 1 1 2
jim 3 2 3
jak 5 3 5
;
run;
Now, I need to create variables p1-p5 that add up the a_vals, b_vals, and c_vals if they match the value. For example, since joe has a value of 1 for a and b, p1 would be sum of a_val and b_val, which is 50. The value of p1 will be zero for both jim and jak, since they have no values of 1. Similarly, p2 will be 0 for jak, 30 for jim, and 40 for joe.
The finished data set would look like this
>name p1 p2 p3 p4 p5
>joe 50 40 0 0 0
>jim 0 30 40 0 0
>jak 0 0 30 0 60
I tried to do this with a do loop like so:
data attempt;
set have;
do i=1 to 5;
p&i=0;
if a=i then p&i=p&i+a_val;
if b=i then p&i=p&i+b_val;
if c=i then p&i=p&i+c_val;
end;
run;
Am I on the right track?
Thanks! Any help appreciated.
You're mixing up macro code and data step code here.
One option:
data want;
set have;
array p p1-p5;
do _i=1 to 5;
p[_i] = sum((a=_i)*&a_val,(b=_i)*&b_val,(c=_i)*&c_val);
end;
run;
You could conceivably loop through the a-c variables in an array also; if so, then you'd need to use symget
to get the value of the macro variable associated with the element of the array. For 3 variables this isn't worth the effort.
This would be something like:
data want;
set have;
array p p1-p5;
array var a b c;
do _i=1 to 5;
do _j = 1 to dim(var);
p[_i] = sum(p[_i],(var[_j]=_i)*symget(cats(vname(var[_j]),'_val')));
end;
end;
run;