Hello,
I am trying to understand where to use quotes with macro variables and where I should not and why----
%let S = F;
data class;
set sashelp.class;
where sex = "&S";
run;
If I use sex = &S without the quotes, it looks for a variable F. So, in the below scenario where I typically would use quotes with a scan function such as scan("Rose,John", 2) , I should not use %scan("&name",2), could you please help me understand why?
%macro first_name(name);
%let first= %scan(&name,2);
%let last = %scan(&name,1);
%put &first &last;
%mend;
%first_name(%str(Rose,John));
The macro language is different. The quote becomes part of the value when used.
One thing to keep in mind with the macro language is that it is supposed to generate code statements, think listing variables or such not actually manipulate data (directly such as parsing address strings). So there are some design elements that are built around simplifying code generation.
Since macros and several of the macro functions use commas as delimiter you may say yourself many headaches by not creating macro variables with commas as part of the value.
What happens in your case below the macro variable gets replace and you are now looking a
%scan(Rose, John, 2) which is going to want to treat "John" as the second parameter and 2 as the delimiter of the string.
Try using %first_name(Rose John);
If the time comes when you want to use only a specific character as a delimiter then I might suggest a character that has little use in other constructs like the pipe, |, character. Space is a default parameter and works just fine for many things.
Consider as a way to specify a delimiter
%macro first_name_alt(name); %let first= %scan(&name.,2,|); %let last = %scan(&name.,1,|); %put First is: &first Second is: &last; %mend; %first_name_alt(Rose|John);
Or a counted loop
%macro name_alt(name); %do i=1 %to %sysfunc(countw(&name,|)); %let first= %scan(&name.,&i,|); %put First &i. is: &first.; %end; %mend; %name_alt(Rose|John Jon|Mary);
The macro language is different. The quote becomes part of the value when used.
One thing to keep in mind with the macro language is that it is supposed to generate code statements, think listing variables or such not actually manipulate data (directly such as parsing address strings). So there are some design elements that are built around simplifying code generation.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.