[英]Creating Intervals using SAS Macro
我正在上SAS課程,還有一個項目要做。 我當然不是在尋找確切的答案(盡管那會很好),但是朝正確方向的大力推動將不勝感激。
問題是要編寫一個宏,以一個人的年齡為單位創建年齡組。 給出的代碼是:
data a ;
infile in1 ;
input name $ age ;
if 30 le age < 33 then agegrp = 30 ;
else if 33 le age < 36 then agegrp = 33 ;
else if 36 le age < 39 then agegrp = 36 ;
else if 39 le age < 42 then agegrp = 39 ;
else if 42 le age < 45 then agegrp = 42 ;
else if 45 le age < 48 then agegrp = 45 ;
else if 48 le age < 51 then agegrp = 48 ;
else if 51 le age < 54 then agegrp = 51 ;
else if 54 le age < 57 then agegrp = 54 ;
else if 57 le age then agegrp = 57 ;
我的工作是編寫一個生成這些if-then / else語句的SAS宏。 這是我到目前為止所擁有的。 我意識到這不會成功,但是我想向大家介紹一下我可以完成這項任務的范圍。
options ls=78 formdlim=' ' ;
%MACRO CODEIT(start= , stop= , count= , old= , new= );
%let x=&start;
%let y=%eval(&start+&count);
if &start
%do x=&start+&count %to &stop %by &count ;
<= &old < &x then &new=&start ;
%let start=&x ;
else if &start
%end ;
<= &old then &new=&start ;
%MEND
data a ;
input age ;
datalines;
30 31 32 33 34 37
38 39 39 41 42 45
46 46 47 49 50 50
52 53 54 55 56 57
%CODEIT(start=30, stop=57, count=3, old=0, new=0);
非常感謝您提前提供的所有幫助。
您有一些小問題,但是(鑒於特定要求)通常會有所下降。
首先,宏需要在數據步驟中執行。 但是,您有數據線,這意味着它無法正常運行-數據線必須是數據步驟的最后一部分。
data a;
input age;
<%codeit call>
datalines;
<data>
;;;;
run;
其次,您的%do
控件略有錯誤。 實際上,您可以通過兩種方式執行此操作; 從理論上講,您可以使用%do
,但實際上您應該使用do
。 我還將更改開始/結束的工作方式,但這只是個人喜好(我將start
不是最低值,而是最低范圍起點; end
應該是最高范圍終點,因為這對我來說是最合乎邏輯的)。
do _iter = &start to &stop by &count;
if _iter. le &old. lt _iter+&count. then &new. = &start.;
end;
if &old. lt &start. then &new.=&start.-&count.;
else if &old. ge &end then &new. = &old.+&count.;
那應該是你的宏。
也就是說,沒有理由為此使用宏。 您可以在數據步驟中完成所有這些工作。 如果這是一個宏類,則可以在%do
編寫大致相同的代碼; 您仍然希望將整個if
包裝在%do
(您將使用&_iter.
或用於迭代變量的任何內容)。
在現實生活中,您可以發布我發布的do循環而沒有宏變量(僅進行硬編碼),或者可以更有效地使用select
語句; 甚至更好的是,使用一種格式( proc format
)來實現重新編碼。 格式確實是最好的選擇,因為這正是它們的用途,並且不需要新的數據步驟就可以完成格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.