无法将宏变量与数据集变量匹配

时间:2015-02-16 01:05:36

标签: sas sas-macro

数据集中的字符变量永远不会与宏变量匹配。 %IF循环永远不会成真。好心劝告。

我试图匹配几个月,因此尝试创建数组并将计数仅限于特定月份。不起作用,因为月份宏变量永远不会与具有月份的数据集变量匹配。

/*create dummy data*/
  data datefile;
  input tran_date date9. cnt 3.;
  datalines;
 13feb2015 5
 10feb2015 4
 11feb2015 3
 05feb2015 8
 08feb2015 5
 01jan2015 1
 20dec2014 1
 31jan2015 2
 23dec2014 2
 12jan2015 1
   ;


 /*calculate month*/
data datefile11;
set datefile;
tran_mon=year(tran_date)*100+month(tran_date);
run;

/*select distinct month*/
proc sql;
create table datefile12 as select distinct(tran_mon)
from datefile11 order by tran_mon;
quit;

/*convert month from numeric to character*/
data datefile11(drop=tran_mon);
informat tran_mon2 $6.;
set datefile11;
tran_mon2=tran_mon;
run;

/*create macro variables through datastep*/
data datefile13;
set datefile12;
monum = cat('mnth',_N_);
run;


data _null_;
set datefile13;
call symput(monum,trim(left(tran_mon)));
run;



/*use array to make separate column for each month and 
  put split count for each month to each colunms*/
  %macro c;
  proc sql noprint;
  select count(1) into :nrow from datefile13;
  quit;

  %let nrow = &nrow;

  data datefile14;
  set datefile11;
  array mon{*} mon_1 - mon_&nrow;
  %do i=1 %to &nrow;
  %if tran_mon2 = &&mnth&i %then %do; %put tran_mon2; 
                                     mon_&i = cnt; %end;
  %else %do; mon_&i = 0 ; %end;
  %end;
  run;
  %mend c;

  %c

1 个答案:

答案 0 :(得分:2)

在数据步骤仍在编译时执行宏%if %then %do检查 - 在数据步骤开始执行时,没有更多机会像这样使用宏逻辑。

尝试反过来 - 改为使用if then do数据步逻辑编写循环。