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,不限.
谢谢!
[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]
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]
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]
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:) -->