2016-02-16 58 views
0

我想根据标识符变量向数据集中插入一条平均值记录。数据集像DS1,如果我们有多对a-b值,我想插入一个变量。比如目标数据集就像DS2。感谢我的朋友。使用proc在sas中插入一条平均记录sql

data DS1; 
input a b c; 
cards; 
1 2 23 
1 2 43 
1 2 23 
1 3 55 
1 4 48 
2 1 43 
2 1 56 
2 2 34 
; 
run; 


data DS2; 
input a b c; 
cards; 
1 2 23 
1 2 43 
1 2 23 
1 2 27.66 
1 3 55 
1 4 48 
2 1 43 
2 1 56 
2 1 44.5 
2 2 34 
; 
run; 

回答

0

为什么选择SQL?如果您要申请特定的解决方案,很好理解为什么。这里有两个方法,一个使用数据步骤,另一个使用SQL。本质上,SQL解决方案计算值,UNION ALL将它们附加到数据集中。 DATA STEP计算通过数据集时的值,只需要一次通过数据,并保持原始数据集的顺序。

data want_datastep; 
set ds1; 
by a b; 
retain sum count; 
if first.b then do; 
    sum=0; 
    count=0; 
end; 

sum=sum+c; 
count+1; 

if last.b and not first.b then do; 
    output; 
    c=sum/count; 
    output; 
end; 
else output; 
run; 


proc sql; 
create table want_sql as 
select * from 
(select ds1.* from ds1 as ds1 
union all 
(select ds1_x.a, ds1_x.b, mean(ds1_x.c) as c 
from ds1 as ds1_x 
group by ds1_x.a, ds1_x.b 
having count(ds1_x.b)>1)) 
order by a, b, c; 
quit; 
+0

这非常有用!朋友,谢谢! – Wayne