首页 > 解决方案 > 在SAS中为proc freq创建循环

问题描述

我有以下数据

DATA HAVE;
input yr_2001 yr_2002 yr_2003 area;
cards;
1 1 1 3
0 1 0 4
0 0 1 3
1 0 1 6
0 0 1 4
;
run;

我想对变量 yr_2001 到 yr_2003 执行以下 proc freq。

proc freq data=have;
table yr_2001*area;
where yr_2001=1;
run;

有没有一种方法可以做到这一点而不必每年重复一次,可能是对 proc freq 使用循环?

标签: loopssasproc

解决方案


两种方式:

1.转置

将计数器变量添加到您的数据中n,然后转置它,n area,然后只保留年份标志等于 1 的值。因为我们在转置组上设置了索引,所以year我们不需要在按组之前对其进行重新排序加工。

data have2;
    set have;
    n = _N_;
run;

proc transpose data=have 
               name=year
               out=have2_tpose(rename = (COL1 = year_flag) 
                               where  = (year_flag = 1)
                               index  = (year)
                               drop   = n
                              );

    by n area;
    var yr_:;
run;

proc freq data=have2_tpose;
    by year;
    table area;
run;

2.宏循环

由于它们都以 开头yr_,因此很容易从中获取所有变量名dictionary.columns并遍历所有变量。我们将使用 SQL 将名称读入 -|分隔的列表并遍历该列表。

proc sql noprint;
    select name
         , count(*)
    into  :varnames separated by '|'
        , :nVarnames
    from dictionary.columns
    where     memname = 'HAVE'
          AND libname = 'WORK'
          AND name LIKE "yr_%"
    ;
quit;

/* Take a look at the variable names we found */
%put &varnames.;

/* Loop over all words in &varnames */
%macro freqLoop;
    %do i = 1 %to &nVarnames.;
        %let varname = %scan(&varnames., &i., |);

        title "&varname.";

        proc freq data=have;
            where &varname. = 1;
            table &varname.*area;
        run;

        title;
    %end;
%mend;
%freqLoop;

推荐阅读