SAS中文论坛

标题: 一个分类百分比的问题 [打印本页]

作者: shiyiming    时间: 2008-11-7 22:16
标题: 一个分类百分比的问题
数据aa
id type
1 a
1    a
1    a
2    a
2    a
2    b
2    b
1    b
2    c
2    c
1    c
3    c
3    c
3    a
2    c
现在期望用datastep求每个id下每类type占这类type的百分比,
作者: shiyiming    时间: 2008-11-7 23:43
标题: Re: 一个分类百分比的问题
why not PROC FREQ?
[code:15tynuju]
proc freq data=a;
table id*type/outpct out=xxx(keep=id type pct_row);
run;
[/code:15tynuju]
作者: shiyiming    时间: 2008-11-8 19:43
标题: Re: 一个分类百分比的问题
我期望用datastep做
作者: shiyiming    时间: 2008-11-8 21:10
标题: Re: 一个分类百分比的问题
you're so weird! I never see a real need of using ONLY data step.
[code:3npde2yf]
data _null_;
        if 0 then set aa;
        length count 8;
        if _n_=1 then do;
                declare HASH ht(ordered:'a');
                ht.defineKey('id', 'type');
                ht.defineData('id', 'type', 'count');
                ht.defineDone();
        end;
        do until (eof);
                set aa end=eof;
                if ht.find() then
                        ht.add(key: id, key: type, data: id, data: type, data: 1);
                else
                        ht.replace(key: id, key: type, data: id, data: type, data: count+1);
        end;
        ht.output(dataset: 'b');
data xxx;
        n_id=0;
        do until(last.id);
                set b;
                by id;
                n_id++count;
        end;
        do until(last.id);
                set b;
                by id;
                pct_row = count/n_id;
                output;
        end;
run;
[/code:3npde2yf]
作者: shiyiming    时间: 2008-11-10 13:58
标题: Re: 一个分类百分比的问题
[code:2qw85ues]data a;
     input id type $;
         cards;
1 a
1 a
1 a
2 a
2 a
2 b
2 b
1 b
2 c
2 c
1 c
3 c
3 c
3 a
2 c
;
run;

proc sort data=a;
     by id type;
run;

data a b c;
     set a;
         by id type;
         if first.id then tot=0;
         if first.type then num=0;
         num+1 ; tot+1;
         if last.id then output b;
         if last.type then output c;
run;

data final;
     merge c(drop=tot) b(keep=id tot);
         by id;
         pct=num/tot*100;
run;[/code:2qw85ues]




欢迎光临 SAS中文论坛 (https://mysas.net/forum/) Powered by Discuz! X3.2