loops - 在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 使用循环?
解决方案
两种方式:
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;
推荐阅读
- xml - 如何在 ASP.net Core 2.1 中生成动态 API
- abap - ABAP CDS 聚合字段根据条件使用 SUM 或 MIN
- react-native - Admob 广告未显示在 React Native Signed Apk 中
- c# - 检查 ASP.NET Core 中是否允许匿名
- python - 将包含熊猫系列的列转换为特征
- php - Codeigniter:更新到 CI4 后,Loader 类出错
- postgresql - 为数据库中所有还没有主键的表添加主键
- python - __index__ 返回非int(类型NoneType):使用张量动态形状创建自定义层
- c# - 无法使用来自 UWP-App 的受信任连接连接到 SQL Server
- arrays - 如何在角度分量中显示多个对象的数据或如何将它们添加到一个数组中