在 SAS 中为 proc freq 创建循环
Creating loop for proc freq in SAS
我有以下数据
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 循环??
两种方式:
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;
我有以下数据
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 循环??
两种方式:
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;