本帖最后由 Emma 于 2015-7-19 21:36 编辑
异常值在SAS中的处理
数据分析少不了和数据中的异常值打交道,Winsorize处理在SAS中经常使用。
Winsorize即极值处理,原理是将数据中的异常值修建,使之与正常分布的最大值与最小值相同。例如,你的数据整体位于[70,90]这个区间,而分析的数据中有些值特别大或者特别小,比如出现了60、65、95与125这种数值,这时Winsorize处理就能够将这些特别大或者特别小的值进行调整,让这些异常值变成你自己定义的一个合理范围中。对于上限,如果定义比90高出10%记为异常值,那么95这个值就会被SAS处理,放在Winsorize处理后的数据集里,而125将被看做异常值,不会放入Winsorize处理后的数据集里;同理,对于下限也是如此。
数据中含有缺失值和重复值时,进行Winsorize处理稍微会复杂一些。可以先对数据排序,但是缺失值首先会对计算造成不小的影响,所以Winsorize处理很方便解决这些常见难题。
SAS Winsorize 处理过程:
%let DSName =sashelp.heart; proc iml; /* SAS/IML moduleto Winsorize each column of a matrix. Input proportion of observations toWinsorize: prop < 0.5. Ex: y= Winsorize(x, 0.1) computes the two-side 10% Winsorized data */ start Winsorize(x,prop); p = ncol(x); /* number of columns */ w = x; /* copy of x */ do i = 1 to p; z = x[,i]; /* copy i_th column */ n = countn(z); /* count nonmissing values */ k = ceil(prop*n); /* number of obs to trim from each tail */ r = rank(z); /* rank values in i_th column */ /* find target values and obs with smaller/largervalues */ lowIdx = loc(r<=k & r^=.); lowVal = z[loc(r=k+1)]; highIdx = loc(r>=n-k+1); highVal = z[loc(r=n-k)]; /* Winsorize (replace) k smallest and klargest values */ w[lowIdx,i] = lowVal; w[highIdx,i] = highVal; end; return(w); finish;
/* test thealgorithm on numerical vars in a data set */ use &DSName; read all var _NUM_into X[colname=varNames]; close; winX = Winsorize(X,0.1);
代码中,矩阵winX包含经过Winsorize处理过的数据,如果你想输出SASWinsorize处理后的数据,数据集属于小数据集,可以使用代码:%letDSName = sashelp.class; 进行实现。
大批量数据处理之前,想验证SAS Winsorize过程是否正确,可以借助SAS/IML计算出来的缩尾均值( Winsorized means),与SAS PROC UNIVARIATE 计算出来的缩尾均值进行比较。
/* Compute Winsorized mean, which is mean of the Winsorized data */ winMean = mean(winX); print winMean[c=varNames f=8.4];
/* Validation: compute Winsorized means byusing UNIVARIATE */ ods exclude all; proc univariate data=&dsname winsorized=0.1; ods output WinsorizedMeans=winMeans; run; ods exclude none;
proc print data=winMeans; var VarName Mean; run;
学习SAS/IML程序,可以参考附件资料。
|