[英]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,
然后僅保留 year 標志等於 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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.