使用宏重命名 SAS 中的变量

Rename variables in SAS using macros

我有一个数据集,其中包含过去 12 个月的借方和贷方周转率以及客户的平均余额。数据看起来像这样

|账号 | Monthly_credit_turover1 || Monthly_credit_turover2 |average_bal_1| average_bal_2

我想用最近 12 个月替换 1、2、3 到 12。例如- average_bal_1 应对应于 average_bal_march,而 average_bal_2 应替换为 average_bal_april。所以对于所有带有 1 的变量应该对应于 3 月,2 对应于 4 月等等

我写的代码是

%macro renaming(i=, mon=);



data bands_macro;
set may_1;
 *this just renames one variable with the two input parameters;
turnover_&i.=sum(MonthlyCreditTurnover&i., MonthlyDebitTurnover&i.);
format tn_bands .;
if turnover_&i. le 0 then tn_bands="1. LE 0";
else if turnover_&i. gt 0 and turnover_&i. le 1000  then tn_bands="2. 0-1k";
else if turnover_&i. gt 1000 and turnover_&i. le 4000  then tn_bands="3. 1k-4k";
else if turnover_&i. gt 4000 and turnover_&i. le 10000  then tn_bands="4. 4k-10k";
else tn_bands="5. >10k";
format ab_bands .;
if averagebalance&i. =999999999999 or averagebalance&i. le 0 then ab_bands="1.LE 0";
else if averagebalance&i. gt 0 and averagebalance&i. le 1000  then ab_bands="2. 0-1k";
else if averagebalance&i. gt 1000 and averagebalance&i. le 5000  then ab_bands="3. 1k-5k";
else if averagebalance&i. gt 5000 and averagebalance&i. le 10000  then ab_bands="4. 5k-10k";
else if averagebalance&i. gt 10000 and averagebalance&i. le 25000  then ab_bands="5. 10k-25k";
else if averagebalance&i. gt 25000 and averagebalance&i. le 50000  then ab_bands="6. 25k-50k";
else ab_bands="7. >50k";
drop MonthlyCreditTurnover&i. MonthlyDebitTurnover&i.;
run;
%mend;
%renaming(i=1,mon=Mar21);
%renaming(i=2,mon=Feb21);

但不幸的是,我在 运行 此代码时收到此警告-

variable turnover2 cannot be rename as turover_april because turnover_april already exists. How do i make these changes in single dataset

所以,这是对简单的数据内步骤宏的一个很好的使用。

data mydata;
  turnover1 = 1;
  turnover2 = 2;
run;

*give two parameters, the numeric value and the month to convert to;
%macro renaming(i=, mon=);
*this just renames one variable with the two input parameters;
rename turnover&i.= turnover_&mon.;
%mend;

data want;
  set mydata;
  *now call each of the macro iterations separately;
  %renaming(i=1,mon=mar)
  %renaming(i=2,mon=apr)
  ;   *just to make the highlighting work;
run;

可以提出一个更好的列表,不过可以肯定的是:

*dataset of the i=mon relationships, you can have this in excel or whatever;
 *and change it every month when the other stuff updates;
*you also may be able to "calculate" all of this?;
data renames;
  input i mon $;  
  datalines;
1 mar
2 apr
;;;;
run;

*pull that into a macro variable using PROC SQL SELECT INTO;
proc sql;
  select cats('%renaming(i=',i,',mon=',mon,')')
    into :renamelist separated by ' '
    from renames;
quit;


*now apply the rename list;
data want;
  set mydata;
  &renamelist.
  ;
run;