标题: 如何直接算出百分比? [打印本页] 作者: shiyiming 时间: 2009-12-25 15:33 标题: 如何直接算出百分比? data a;
input group $ x y;
cards;
a 12 14
a 9 32
b 13 15
b 21 25
b 10 14
c 20 12
;
run;
想计算出每个group中的x值的和与所有X的总和的比例. 如果分两步做,很简单,一次算每个group的和,然后再算总和,两个比一下.
但如果在一步里实现的话,该如何做? SQL或者data step,不限.
谢谢!作者: shiyiming 时间: 2009-12-25 16:23 标题: Re: 如何直接算出百分比? [code:1v49n4sb]data a;
input group $ x y;
cards;
a 12 14
a 9 32
b 13 15
b 21 25
b 10 14
c 20 12
;
data b;
sum_x=0;
do _n_=1 by 1 until(last.group);
set a;
by group;
sum_x+x;
end;
do _n_=1 to _n_;
set a;
pct_x=round(x/sum_x,0.01);
output;
end;
run;[/code:1v49n4sb]作者: shiyiming 时间: 2009-12-26 01:42 标题: Re: 如何直接算出百分比? 谢谢hopewell.
我想要的是group的和/总和.
比如:
group a: 21/85
group b: 44/85
group c: 20/85
随便问一下: proc sql里有没有可能用case算总和,或inter query的方法算总和.作者: shiyiming 时间: 2009-12-26 03:07 标题: Re: 如何直接算出百分比? I hope this works for you. <!-- s:) --><img src="{SMILIES_PATH}/icon_smile.gif" alt=":)" title="Smile" /><!-- s:) -->
[code:3otk6x9h]data a;
input group $ x y;
cards;
a 12 14
a 9 32
b 13 15
b 21 25
b 10 14
c 20 12
;
run;
proc sql;
create table results as
select x.group,
x.sumX / y.sumX as pct
from (select group,
sum(x) as sumX
from a
group by group
) as x
inner join
(select sum(x) as sumX
from a
) as y
on 1 = 1;
run;
[/code:3otk6x9h]作者: shiyiming 时间: 2009-12-26 10:35 标题: Re: 如何直接算出百分比? data step
[code:1hh18sc7]data b(keep=group pct);
subtotal=0;
if _n_=1 then
do until(eof);
set a end=eof;
total+x;
end;
do _n_=1 by 1 until(last.group);
set a;
by group;
subtotal+x;
end;
pct=subtotal/total;
run;[/code:1hh18sc7]
sql
[code:1hh18sc7]proc sql;
create table c as
select group,sum(x)/total as pct
from a, (select sum(x) as total from a)
group by group;
quit;[/code:1hh18sc7]
proc tabulate
[code:1hh18sc7]ods output table=d(keep=group x_pctsum_0 rename=(x_pctsum_0=pct));
proc tabulate data=a;
var x;
class group;
table group,x*pctsum;
run;
ods output close;[/code:1hh18sc7]作者: shiyiming 时间: 2009-12-26 12:00 标题: Re: 如何直接算出百分比? I like the [i:o6biegf4]proc tabulate[/i:o6biegf4] one. Thank you hopewell! <!-- s:) --><img src="{SMILIES_PATH}/icon_smile.gif" alt=":)" title="Smile" /><!-- s:) -->作者: shiyiming 时间: 2009-12-26 14:37 标题: Re: 如何直接算出百分比? 不佩服不行. 谢谢上面几位!作者: shiyiming 时间: 2010-1-24 15:36 标题: Re: 如何直接算出百分比? 我也来学学 谢谢各位作者: shiyiming 时间: 2010-2-17 07:15 标题: Re: 如何直接算出百分比? yet another solution using PROC FREQ:
*****************************;
data a;
input group $ x y;
cards;
a 12 14
a 9 32
b 13 15
b 21 25
b 10 14
c 20 12
;
run;