BookmarkSubscribeRSS Feed
Hagay
SAS Employee

בשבוע שעבר ראינו איך ניתן להגדיר משתנה מאקרו של SAS ע"י הפקודה %let. דרך נוספת ליצירה של משתנה מאקרו היא בעזרת proc sql המוכר והטוב.

 

מילת המפתח המאפשרת את הקסם הזה היא into אשר אומרת ל SAS להפנות את הנתון המתקבל לתוך משתנה מאקרו שאנחנו מציינים יחד עם נקודתיים לפני השם שלו. אם אנחנו לא משתמשים בשום פונקציה מסכמת אז הערך שמוזן למשתנה המאקרו מבוסס על השורה הראשונה בטבלה, לדוגמא:

 

proc sql noprint;
	select name
	into :first_name
	from sashelp.class;
quit;
%put &=first_name; * Assuming we know the value in the first row in the table or just do not care;

 

פונקציות סיכומיות מאפשרות לנו יותר שליטה על הערך שמוזן למשתנה המאקרו מתוך הטבלה שלנו:

proc sql noprint;
	select max(name) 
	into :max_name
	from sashelp.class;
quit;
%put &=max_name;

היתרון בשיטה זו שניתן בבת אחד גם לחשב את הערך שרוצים וגם ליצור ממנו משתנה מאקרו לשימוש בהמשך התוכנית שלנו:

proc sql noprint;
	select catx('-',max(name),min(name))
	into :max_min_names
	from sashelp.class;
quit;
%put &=max_min_names;

במידה והערך שאנחנו רוצים לשמור לתוך משתנה המאקרו הוא מספר, SAS ממיר אותו למחרוזת לפני השמירה כמשתנה מאקרו – משתני מאקרו מכילים תמיד טקסט, גם אם לפעמיים הטקסט מורכב מספרות ונראה כמו מספר. המרה זו עושה שימוש בפורמט שמוגדר על עמודה בטבלת המקור או בפורמט ברירת המחדל. לעיתים קרובות המרה זו מוסיפה רווחים לפני המספר עצמו ואם אנחנו רוצים להעלים אותם ניתן לעשות שימוש באופציה trimmed:

proc sql noprint;
	select max(age) 
	into :max_age
	from sashelp.class;
quit;
%put &=max_age; * Note the spaces ahead of the number;

proc sql noprint;
	select max(age) 
	into :max_age trimmed
	from sashelp.class;
quit;
%put &=max_age; * No spaces;

ניתן גם לשמור מספר משתנים בבת אחת:

proc sql noprint;
	select 
		max(weight),
		min(weight) 
	into 
		:max_weight trimmed,
		:min_weight trimmed
	from sashelp.class;
quit;
%put &=max_weight &=min_weight;

ואפילו יותר נחמד היא האופציה separated by המאפשרת לנו לשרשר כמה ערכים ביחד לתוך משתנה מאקרו אחד מופרדים בתווים לבחירתנו:

proc sql noprint;
	select distinct  age
	into :all_ages separated by ","
	from sashelp.class;
quit;
%put &=all_ages;

חגי

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

Discussion stats
  • 0 replies
  • 468 views
  • 0 likes
  • 1 in conversation