0
votes

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.

2

2 Answers

1
votes

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;
0
votes

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;