-1

I need to loop over some macro variables in my data step i have tried to define the macro variable and build them dynamically in the data step like this

DATA _NULL_;
 call symputx('_rbank_1',put(001,z3.));
 call symputx('_rwebhost_1','company1.myhost.com');

 call symputx('_rbank_2',put(008,z3.));
 call symputx('_rwebhost_2','company2.myhost.com');

 call symputx('_rbank_3',put(008,z3.));
 call symputx('_rwebhost_3','company3.myhost.com');

RUN;

%let _rbank_1 = &_rbank_1;
%let _rwebhost_1 = &_rwebhost_1;
%let _rbank_2 = &_rbank_2;
%let _rwebhost_2 = &_rwebhost_2;
%let _rbank_3 = &_rbank_3;
%let _rwebhost_3 = &_rwebhost_3;


data test;
 do cnt=1 to 3;
  macroString=compress("&_rwebhost_"||cnt);
  marcroValue=macroString; 
 end;
run;

But the output of macroValue is "&_rwebhost_3" and i need it to be the value not the name.

I can do this in macro but i really need it in a data step . Normally in other programming language i would define a hash table but that doesn't seem to be that simple in sas datastep.

havmaage
  • 573
  • 7
  • 25

2 Answers2

1

The oposite of symput is symget

data test;
 do cnt=1 to 3;
  macroString=symgetc(cats("_rwebhost_",put(cnt,BEST32.)));
  marcroValue=symgetn(cats("_rbank_",put(cnt,BEST32.)));
  output; 
 end;
run;
Lee
  • 1,427
  • 9
  • 17
0

Use the SYMGET() function to retrieve the value of a macro variable whose name is not known in advance.

%let _rbank_1 = 001;
%let _rwebhost_1 = company1.myhost.com;
%let _rbank_2 = 008;
%let _rwebhost_2 = company2.myhost.com;
%let _rbank_3 = 008;
%let _rwebhost_3 = company3.myhost.com;

data test;
 do cnt=1 to 3;
   bank = symget(cats('_rbank_',cnt));
   webhost= symget(cats('_rwebhost_',cnt));
   put cnt= bank= webhost= ;
 end;
run;

But if you need the values in dataset variables then store them in a dataset instead of in macro variables. For example you could use the POINT= option on the SET statement to pick which observation to read.

data company ;
  input bank $3. webhost $20. ;
cards;
001 company1.myhost.com
008 company2.myhost.com
008 company3.myhost.com
;

data test;
  do cnt=1 to 3;
    set company point=cnt;
    put cnt= bank= webhost= ;
  end;
run;
Tom
  • 47,574
  • 2
  • 16
  • 29
  • The changes to my solution are only minimal. – Lee Apr 29 '19 at 13:02
  • @lee Yes. I fleshed it out more to add example of how to avoid using macro variables instead. – Tom Apr 29 '19 at 13:18
  • You are right but thee code given by him is only an example. Most times it comes from a little more obscure program which an high change of other problems. – Lee Apr 29 '19 at 14:01
  • 1
    Exactly. Most uses of macro "arrays" are examples of coding gone a long way down the wrong track. – Tom Apr 29 '19 at 14:46