我有数据集,其中有州、玉米和棉花。我想在SAS中创建一个新变量Corn_Pct (国家玉米产量占全国玉米产量的百分比)。Cotton_pct也是如此。数据示例:(数字不是实数)
State Corn Cotton
TX 135 500
AK 120 350
...有人能帮上忙吗?
发布于 2017-05-09 12:56:45
您可以使用一个简单的Proc SQL来完成此操作。将数据集设置为"Test",
Proc sql ;
create table test_percent as
select *,
Corn/sum(corn) as Corn_Pct format=percent7.1,
Cotton/sum(Cotton) as Cotton_Pct format=percent7.1
from test
;
quit;如果您有许多列,则可以使用Arrays和do loops每次自动生成百分比。
发布于 2017-05-09 13:24:39
我在Inner Query中计算了列的总数,然后使用Cross Join在外部查询中使用该总数进行计算
嘿,试试这个:-
/*My Dataset */
Data Test;
input State $ Corn Cotton ;
cards;
TK 135 500
AK 120 350
CK 100 250
FG 200 300
run;
/*Code*/
Proc sql;
create table test_percent as
Select a.*, (corn * 100/sm_corn) as Corn_pct, (Cotton * 100/sm_cotton) as Cotton_pct
from test a
cross join
(
select sum(corn) as sm_corn ,
sum(Cotton) as sm_cotton
from test
) b ;
quit;
/*My Output*/
State Corn Cotton Corn_pct Cotton_pct
TK 135 500 24.32432432 35.71428571
AK 120 350 21.62162162 25
CK 100 250 18.01801802 17.85714286
FG 200 300 36.03603604 21.42857143发布于 2017-05-09 17:04:36
这里有一个使用proc means和data step的替代方案
proc means data=test sum noprint;
output out=test2(keep=corn cotton) sum=corn cotton;
quit;
data test_percent (drop=corn_sum cotton_sum);
set test2(rename=(corn=corn_sum cotton=cotton_sum) in=in1) test(in=in2);
if (in1=1) then do;
call symput('corn_sum',corn_sum);
call symput('cotton_sum',cotton_sum);
end;
else do;
Corn_pct = corn/symget('corn_sum');
Cotton_pct = cotton/symget('cotton_sum');
output;
end;
run;https://stackoverflow.com/questions/43861065
复制相似问题