基于SAS按州、县、污染物统计年AQI超100天数及多污染物判定
SAS实现空气质量数据统计与多污染物超标判定
一、无需子集化数据的宽表统计实现
要完成按州、县、污染物统计每年AQI>100的天数并输出宽表,无需提前子集化原数据,可通过PROC SQL统计+PROC TRANSPOSE转宽的组合实现,全程基于原数据集操作:
- 直接在统计逻辑中计算超标天数,无需创建子集:
proc sql; create table aqi_exceed_counts as select state, county, year(date) as year, /* 从日期字段提取年份 */ pollutant, sum(case when aqi > 100 then 1 else 0 end) as exceed_days /* 统计AQI超标的天数 */ from original_air_data group by state, county, calculated year, pollutant; quit;
- 将统计结果转成宽表,每个州-县-年份组合为一行,各污染物作为列:
proc transpose data=aqi_exceed_counts out=aqi_exceed_wide prefix=exceed_days_; by state county year; /* 指定分组关键字 */ id pollutant; /* 用污染物名称作为列名 */ var exceed_days; /* 转置的数值字段 */ run;
若不需要按年份拆分,只需州-县组合一行,去掉year在by和select中的字段即可。
二、判定同一州-县-日期下的多污染物超标情况
要识别同一州、县、日期内是否存在多种AQI>100的污染物,可通过分组统计超标污染物数量实现,同样无需子集化原数据:
方法1:生成日期级别的超标标记表
直接输出每个州-县-日期的超标污染物数量及是否存在多污染物超标:
proc sql; create table date_level_exceed_check as select state, county, date, count(distinct pollutant) as exceed_pollutant_count, /* 统计该日期超标污染物种类数 */ case when count(distinct pollutant) > 1 then 'Y' else 'N' end as has_multi_exceed /* 标记是否多污染物超标 */ from original_air_data where aqi > 100 group by state, county, date; quit;
方法2:保留原数据所有行并添加标记
如果需要在原数据集的每一行上标注该日期是否存在多污染物超标,用左连接实现:
proc sql; create table air_data_with_multi_flag as select a.*, coalesce(b.has_multi_exceed, 'N') as has_multi_exceed /* 无超标时标记为N */ from original_air_data a left join ( select state, county, date, case when count(distinct pollutant) > 1 then 'Y' else 'N' end as has_multi_exceed from original_air_data where aqi > 100 group by state, county, date ) b on a.state = b.state and a.county = b.county and a.date = b.date; quit;
内容的提问来源于stack exchange,提问作者mennit
相关产品推荐
相关产品推荐

