2017-05-09 12 views
0

州、コーン、およびコットンを持つデータセットがあります。私はSASに新しい変数、Corn_Pct(国のコーン生産量に対する国家コーン生産量の割合)を作成したいと考えています。 Cotton_pctと同じです。データの サンプル:(数字は本物ではありません)列の合計を使用して新しい変数を作成する

State Corn Cotton 
    TX 135 500 
    AK 120 350 
    ... 

誰が助けることはできますか?

+0

投稿したサンプルデータにはどのような出力が期待されますか?何を試しましたか?どのように結果があなたが望むものと異なっていたのですか? – Tom

+0

私は2つの新しい列を取得する必要があります。最初は[Corn_pct =(corn/sum(corn))* 100;]を試しましたが、これはちょうど100を与えました。その番号を取り戻す。私はこれを行う方法があることを知っている、私はそれを覚えていないことができます。 –

答えて

1

単純なProc SQLを使用してこれを行うことができます。データセットは、「テスト」とする、

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; 

あなたは多くの列を持っている場合は、自動的に毎回割合を生成するArraysdo loopsを使用することができます。

0

私はInner Queryの列の合計を計算し、その後Cross Join

を使用して外部クエリで計算のためにその合計を使用ねえ、この試してみる: - あなたがproc meansを使用して選択肢を持っている。ここ

/*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 
0

をおよび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; 
関連する問題