3 weeks ago
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?
If an observation has value C, I want to categorize this as FACTOR1 = 1.
I tried doing this:
%do i=1 %to %sysfunc(countw(&list));
if variable in: (%scan(&allfactors, &i)) then %scan(&list, &i)=1;
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.
3 weeks ago
%let factor1 = 'a' 'b' 'c'; %let factor2 = 'd' 'e' 'f'; data WANT; VAR='e'; %macro loop; %local i; %do i=1 %to 2; FACTOR&i. = ( VAR in (&&factor&i.) ); %end; %mend; %loop run;
3 weeks ago - last edited 3 weeks ago
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) ; %end;
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) ; %end;