Hi,
I have 3 datasets named S1 S2 S3 in the default work directory[i.e. produced from the last executed step], which should be used in a merge statement and the variable names should be renamed based on the numeric they are carrying.
I would like to create a macro for this process. These input datasets(S1 S2 S3) can change to anything(eg:outk1 outk2 outk3).
Without macro i've wrote the below code, would like to do it with the help of macro so that later based on the inputs(like s1 s2 s3 ) it will do my job accordingly.
finalS;
merge s1(rename=(var_a=a1 var_b=b1 var_c=c1)
s2(rename=(var_a=a2 var_b=b2 var_c=c2))
s3(rename=(var_a=a3 var_b=b3 var_c=c3))
run;
any thoughts, comments?
Hello,
If i understand you correctly :
%macro merge(dsname);
data final&dsname.;
merge %do i=1 %to 3;
&dsname.&i. (rename=(var_a=a&i. var_b=b&i. var_c=c&i.))
%end;
;
run;
%mend;
%merge(S)
Note : untested.
This macro accepts parameters that specify data set name prefixes and variable name prefixes and number of each thereof.
If you want a more abstract macro, say one that examines the members of a library and discovers the common names of the variables therein, you will need a more complex process.
Example:
%macro enwidening_rename(data=, n=, var=, m=);
%local i j letter;
%do i = 1 %to &n;
&data.&i ( rename = (
%do j = 1 %to &m;
%let letter = %sysfunc(byte(64+&j));
&var._&letter = &letter.&i
%end;
))
%end;
%mend;
data s1 s2 s3;
var_a = 010; var_b = 020; var_c = 030; output s1;
var_a = 110; var_b = 120; var_c = 130; output s2;
var_a = 210; var_b = 220; var_c = 230; output s3;
run;
options mprint;
data all;
merge
%enwidening_rename(data=s, n=3, var=var, m=3)
;
* no by statement ?, be careful and certain;
run;
Result
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
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.
Ready to level-up your skills? Choose your own adventure.