Anthony Martin
Anthony Martin

Reputation: 787

How to call a macro variable based on a condition

I have a dataset in SAS with

What i want to do is to create a new variable total which is equal to vark if condition=k. I can do it by several if... else statement (it is what I do for now), but I did not manage to do it in a more compact and elegant way.

I tried

data want;
set have;
    call symput(condition, temp);
    total=var&temp;
run;

But it does not work... At best with some tries with resolve instructions I wan get a total value that equals 'var01' and so on, but just the characters, not the values associated to the variable var01

My goal is to do better than

data want  ;
set have (keep=noi nomen var01-var20 lprm condition ag);
if condition="01" then varpr=var01;
else if condition="02" then varpr=var02;
else if condition="03" then varpr=var03;
else if condition="04" then varpr=var04;
else if condition="05" then varpr=var05;
else if condition="06" then varpr=var06;
else if condition="07" then varpr=var07;
else if condition="08" then varpr=var08;
else if condition="09" then varpr=var09;
else if condition="10" then varpr=var10;
else if condition="11" then varpr=var11;
else if condition="12" then varpr=var12;
else if condition="13" then varpr=var13;
else if condition="14" then varpr=var14;
else if condition="15" then varpr=var15;
else if condition="16" then varpr=var16;
else if condition="17" then varpr=var17;
else if condition="18" then varpr=var18;
else if condition="19" then varpr=var19;
else if condition="20" then varpr=var20;
run;

Thanks

Upvotes: 0

Views: 525

Answers (3)

Here you can create a small macro with loop.

Idea is

%Macro cond;

%do i=1 %to 20;

If condition="&i" then out_var=in_&var;

%end;

%mend;

Use this macro in data step.

I hope this can solve your purpose.

Upvotes: 0

Joe
Joe

Reputation: 63424

You can't use a macro variable that way - it has to be defined outside of the data step.

However, you can use arrays for this, if I understand your purpose.

data want;
  set have;
  array var[20] var01-var20;
  total=var[condition];
run;

Upvotes: 1

Reeza
Reeza

Reputation: 21264

A different solution, not using arrays, using the vvaluex function:

varpr = vvaluex(catt('var', condition));

http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a002233818.htm

Upvotes: 3

Related Questions