SAS中變量值標籤的使用

一、 Using Format to Enhance Your Output

        本次例子爲《Learning SAS by Example, A Programmers Guide》第五章的內容。目前有survey數據集。需要對變量裏面的值貼上適當的標籤增加輸出結果的可讀性。

1.1 讀取survey.txt數據

        我們可以查看survey.txt數據的格式

001 M 23 28000 1 2 1 2 3
002 F 55 76123 4 5 2 1 1
003 M 38 36500 2 2 2 2 1
004 F 67 128000 5 3 2 2 4
005 M 22 23060 3 3 3 4 2
006 M 63 90000 2 3 5 4 3
007 F 45 76100 5 3 4 3 3

        在SAS系統中進行導入txt文件

data sas.survey;
   infile 'G:\survey.txt' pad;
   input ID : $3.
         Gender :$1.
         Age
         Salary
         (Ques1-Ques5)($1.+1);
run;
proc print data = sas.survey;
id ID;
run;

        未使用 proc format 打印的結果爲:

1.2 Using PROC FORMAT to create user-defined formats

        我們使用proc format進行對每個變量設置用戶自定義的格式

proc format;
value $gender 'M' = 'Male'
              'F' = 'Female'
			  ' ' = 'Not entered'
			other = 'Miscoded';

value age low-29  = 'Less than 30'
          31-50  = '30 to 50'
		  51-high = '51+';

value $likert '1' = 'Strongly disagree'
              '2' = 'Disagree'
			  '3' = 'No opinion'
			  '4' = 'Agree'
			  '5' = 'Strongly agree';

run;

        需要注意的幾點:


  1. 字符型變量在定義值標籤時,要在標籤格式前面加上 $
  2. proc format 後面需要添加分號
  3. 每一個 value 的變量進行值標籤設置時,在最後面才輸入分號,比如上面的例子中 ‘M’ = ‘Male’ 後面是沒有分號的,需要對下一個值進行設置時,我們回車後接着輸入即可,而在 other = ‘Miscoded’ 此時我們已經輸入完成,就在後面添加分號
  4. 關於 gender 的值標籤的設置 ,這裏給出作者比較詳細的解釋:
    Values for Gender are stored as M and F. Associating the $GENDER format with the variable Gender results in M displaying as Male, F displaying as Female, and missing values displayed as Not entered. The keyword other in the VALUE statement causes the text Miscoded to be printed for any characters besides M, F, or a missing value.
  5. 關於 low 和 high ,這裏同樣給出作者的解釋:
    In the AGE format, the keywords LOW and HIGH refer to the lowest nonmissing value and the highest value, respectively.
    Note: The keyword LOW when used with character formats includes missing values.

1.3 Adding a FORMAT statement in PROC PRINT

        設置後好,我們就可以在proc print過程步中添加 format 的語句

title'Data Set SURVEY with Formatted Values';
proc print data=survey;
id ID;
var Gender Age Salary Ques1-Ques5;
format Gender $gender.
       Age    age.
	   Ques1-Ques5 $likert.
	   Salary dollar11.2;
run;

        這裏說明一下,在format後的使用值標籤的時候,不要忘了圓心點,如上述程序中,gender、age 和 likert 後面都是帶有一個圓心點。
        打印的結果爲:

        歡迎共同學習交流~

二、參考資料

[1].《Learning SAS by Example, A Programmers Guide》
[2]. SAS中標籤(Label)的使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章