Using scan( ) to pull macro string

Frequent Learner
Posts: 1

Using scan( ) to pull macro string



I have a dataset where I am trying to categorize values of a variable into groups.

Say I want to categorize as so:

a, b, or c = factor1

d, e, or f = factor2


I have the following codes.


%let factor1 = %str("a", "b", "c");

%let factor2 = %str("d", "e", "f");



(say I have around 30 of these different factors)


I grouped all these macros into one big list:

%let allfactors = &factor1 &factor2 &factor3 etc


I also have a list with all the categories I want:

%let list = factor1 factor2 factor 3 etc.


How do I create a code where I scan the place of the &factor and categorize the observation's value according to the place of the &list?


For example,

If an observation has value C, I want to categorize this as FACTOR1 = 1.


I tried doing this:

%macro test(data=);
data &data._o;
set &data.;
%do i=1 %to %sysfunc(countw(&list));
if variable in: (%scan(&allfactors, &i)) then %scan(&list, &i)=1;
%mend test;





When I run this code, the entire macro for ALLFACTORS is considered. For example, the &i includes only value 'a' but I want the value of &i to be according to the &list placement (e.g. i=1 should be factor1 in LIST and &factor1 in ALLFACTORS.


How should I change my code?


Thank you, and apologies in advance if this is confusing.



Posts: 2,370

Re: Using scan( ) to pull macro string

Like this?


%let factor1 = 'a' 'b' 'c';
%let factor2 = 'd' 'e' 'f';

data WANT;
  %macro loop;
    %local i;
    %do i=1 %to 2;
      FACTOR&i. = ( VAR in (&&factor&i.) );

e 0 1


Super User
Super User
Posts: 8,126

Re: Using scan( ) to pull macro string

[ Edited ]

Sample data would help a lot in explaining your problem.  Also having a working SAS program before trying to figure out how to generate it with macro logic would help a lot.


Sounds like you want to place the list of values into separate macro variables and then also have a macro variable that lists the macro variables? In that case list the NAMES of the macro variables, not their values.

%let color='red' 'green';
%let style='modern' 'classic';
%let allfactors = color style ;

And the code you want to generate is essentially 

color = MYVAR in ('red' 'green');
style = MYVAR in ('modern' 'classic');

So your %DO loop should look like:

%local i factor ;
%do i=1 %to %sysfunc(countw(&allfactors));
 %let factor=%scan(&allfactors,&i);
 &factor = MYVAR in (&&&factor) ;

 If you just want to name the factors FACTOR1, FACTOR2, etc then you don't need the list. Instead you just need to know how many factors there are.

%local i;
%do i=1 %to &n_factors ;
 factor&i = MYVAR in (&&factor&i) ;
Ask a Question
Discussion stats
  • 2 replies
  • 3 in conversation