2014-01-30 137 views
4

假設我們有一些數據集people,其中包含4級(1,2,3,4)的分類變量income。我們如何在SAS中編碼?它會是:SAS中的虛擬變量

data people; 
set people; 
if income=1 then income1=1; 
else if income=2 then income2=1 
else if income =3 then income3=1; 
run; 

換句話說,這將創建三個虛擬變量的四個級別。這是正確的嗎?

回答

1

我修改了下面的代碼。這會給出一個3個虛擬編碼變量。 income = 4將成爲您的參考代碼。

data people_dummy; 
     set people; 
     if income=1 then income1=1 ; else income1=0; 
     if income=2 then income2=1 ; else income2=0; 
     if income=3 then income3=1 ; else income3=0; 
run; 
+0

您必須在else語句之前的行後添加分號。 – Damien

+0

謝謝@Damien。 – forecaster

5

更靈活的方法是使用數組。

data people; 
set people; 
array incomes income1-income4; 
do _t = 1 to dim(incomes); 
    if income=_t then income[_t] = 1; 
    else if not missing(income) then income[_t]=0; 
    else income[_t]=.; 
end; 
run; 
1

而且我會寫更一般的東西。

%macro cat(indata, variable); 
    proc sql noprint; 
    select distinct &variable. into :mvals separated by '|' 
    from &indata.; 

    %let mdim=&sqlobs; 
    quit; 

    data &indata.; 
    set &indata.; 
    %do _i=1 %to &mdim.; 
     %let _v = %scan(&mvals., &_i., |); 
     if &variable. = &_v. then &variable.&_v. = 1; else &variable.&_v = 0; 
    %end; 
    run; 
%mend; 

%cat(people, income); 
1

你不需要寫「else」。下面還將努力:

income1_ind=(income1 eq 1); 
    income2_ind=(income2 eq 2); 
0

代碼: -

proc sql noprint; 
select distinct 'income' || strip(put(income,8.)) into :income_var separated by ' ' 
from people; 
quit; 

data people(rename = (in = income)); 
set people(rename = (income = in)); 
length &income_var. 8; 
array tmp_arr(*) income:; 
do i = 1 to dim(tmp_arr); 
    if in eq i then tmp_arr(i) = 1; 
    else tmp_arr(i) = 0; 
end; 
drop i; 
run; 

工作:以上SAS代碼是動態的,適用於任何數量的收入變量的水平的工作,因爲它會自動創建根據變量數輸入人員數據集中不同級別的數量。

根據收入變量的值,數據步驟將相應變量設置爲值1,其他變量設置爲0。