2017-03-24 57 views
-2

我的分類變量有四個級別 - 東,西,北,南。我希望這些級別是1,2,3,4(數字形式)。我如何在SAS中做到這一點?謝謝!將分類字符變量轉換爲SAS中的數字值

+1

如果VAR = '東' 然後new_var = 1;如果var ='west',那麼new_var = 2; ...? – pinegulf

+0

請提供一些關於如何使用這些值的更多上下文。這可能是你只需要格式化它們(查看'proc格式'),這將避免改變值。要符合有效的SO問題,您還應該發佈一些您試過的代碼 – Longfish

回答

0

最簡單和最恰當的方法是創建格式:

proc format; 
    value $numvar 
     east = 1 
     west = 2 
     north = 3 
     south = 4 
    ; 
run; 

在數據步驟中,您只需要創建新的數值變量:

/* data step code */ 
new_var = put(your_categorical_variable, $numvar.); 
/* data step code */ 

這種方法的好處是,你可以很容易地如有必要更改編碼 - 僅在proc格式中進行更改,而不是在轉換變量的所有數據步驟中進行更改。使用硬編碼是不可能的

if var='east' then new_var=1 ... 
+1

問題很模糊,但我認爲他們需要一個數字變量。以上將會產生new_var字符。 – Quentin

+0

@Quentin,我同意。如果需要確切的數字,我們可以在SET語句和new_var爲數字前的數據步驟中添加'LENGTH new_var 8;'。它會在日誌中引起警告。所以更好的決定是'做new_var = input(put(your_categorical_variable,$ numvar。),1);' – redFox

+1

或者可以製作用戶生成的信息而不是格式。 – Quentin

1

有理由更喜歡INFORMAT而不是FORMAT來創建數值變量。

proc format cntlout= cntl; 
    value $numvar 
     east = 1 
     west = 2 
     north = 3 
     south = 4 
     other=. 
    ; 
    invalue numvar(upcase) 
     EAST = 1 
     WEST = 2 
     NORTH = 3 
     SOUTH = 4 
     other=. 
    ; 
    run; 
data _null_; 
    do x='norTH' , 'South' , 'East' , 'west' , 'outer'; 
     length b 8; 
     b = put(x,$numvar.); 
     c = input(x,numvar.); 
     put _all_; 
     end; 
    run;  

通知的不同的結果,並且沒有轉換注:

43   data _null_; 
44   do x='norTH' , 'South' , 'East' , 'west' , 'outer'; 
45    length b 8; 
46    b = put(x,$numvar.); 
47    c = input(x,numvar.); 
48    put _all_; 
49    end; 
50   run; 

NOTE: Character values have been converted to numeric values at the places given by: (Line):(Column). 
     46:11 
x=norTH b=. c=3 _ERROR_=0 _N_=1 
x=South b=. c=4 _ERROR_=0 _N_=1 
x=East b=. c=1 _ERROR_=0 _N_=1 
x=west b=2 c=2 _ERROR_=0 _N_=1 
x=outer b=. c=. _ERROR_=0 _N_=1 
NOTE: DATA statement used (Total process time):