SAS在没有PROC手段的情况下查找中位数

时间:2013-12-08 00:38:40

标签: sas

我有一个数据集(已按血压变量排序)

Blood Pressure

87

99

99

109

111

112

117

119

121

123

139

143

145

151

165

198

我需要在不使用proc手段的情况下找到中位数。 现在对于这些数据,有16个观测值。中位数为(119 + 121)/ 2 = 120。

我如何进行编码,以便无论有多少观察结果,我总能找到中位数。适用于偶数观测和奇数观测的代码。

当然,不允许使用PROC。

谢谢。

2 个答案:

答案 0 :(得分:1)

我使用FCMP功能。这是我个人图书馆的通用分位数功能。由于中位数为50%,因此可行。

options cmplib=work.fns;
data input;
input BP;
datalines;
87
99
99
109
111
112
117
119
121
123
139
143
145
151
165
198 
;run;

proc fcmp outlib=work.fns.fns;
function qtile_n(p, arr[*], n);
    alphap=1;
    betap=1;

    if n > 1 then do;
        m = alphap+p*(1-alphap-betap);
        i = floor(n*p+m);
        g = n*p + m - i;
        qp = (1-g)*arr[i] + g*arr[i+1];
    end;
    else 
        qp = arr[1];
    return(qp);
endsub;
quit;

proc sql noprint;
select count(*) into :n from input;
quit;

data _null_;
set input end=last;
array v[&n] _temporary_;

v[_n_] = bp;

if last then do;
    med = qtile_n(.5,v,&n);
    put med=;
end;
run;

答案 1 :(得分:0)

假设您有一个名为HAVE的数据集按变量BP排序,您可以尝试:

data want(keep=median);
  if mod(nobs,2) = 0 then do; /* even number if records in data set */
     j = nobs / 2;
     set HAVE(keep=bp) point=j nobs=nobs;
     k = bp;  /* hold value in temp variable */
     j + 1;
     set HAVE(keep=bp) point=j nobs=nobs;
     median = (k + bp) / 2;
     end;
  else do;
     j = round( nobs / 2 );
     set HAVE(keep=bp) point=j nobs=nobs;
     median = bp;
     end;
   put median=; /* if all you want is to see the result */
   output;      /* if you want it in a new data set */
   stop;        /* stop required to prevent infinite loop */
run;

这是“老式”代码;我确信有人可以使用哈希对象显示另一个解决方案,这可能会消除首先对数据进行排序的要求。