I am recoding a large number of coded character variables into dummy variables. I am using one of the published routines that creates a series of If-Then statements and then stores then in a character variable in a SAS dataset. Unfortunately, that routine did not indicate how to use the character variable to create executable SAS datastep statements.
Here's an example:
Dataset work.dummy code...
Obs SAS_Code_Var
1 If orig_var eq 'a' Then orig_var_a =1; Else orig_var_a =0;
2 If orig_var eq 'b' Then orig_var_b =1; Else orig_var_b =0;
What is a good way to use this variable to implement executable SAS code?
is this a one time change or being implemented as part of larger process.
if its a one time change, i'd proc print the data set and copy and paste it into my SAS code.
otherwise i think you need to go into macro coding using %put to create a program and then %include it.
Try
data dummy;
set dummy;
call execute(SAS_Code_Var);
run;
If you want a shorter solution: orig_var_a = (orig_var eq 'a'); will give you the same result.
The easiest way is to use a a data step to write a program and then %INCLUDE the generated code. You can also use CALL EXECUTE to generate the program, but that is much harder to debug since you do not have a physical file that you examine for mistakes.
Note that you cannot just execute an IF statement, it has to be part of a data step.
filename code temp;
data _null_;
set work.dummy ;
file code ;
put SAS_code_var;
run;
data want ;
set have ;
%inc code / source2 ;
run;
Depending on how this code is generated (i.e. a macro) perhaps you could embed that directly in a data step?
To be honest, if your code is just a series of if statements over a set of variables why not do:
proc sql;
select distinct NAME
into :LIST
from SASHELP.VCOLUMN
where LIBNAME="WORK" and MEMNAME="ABC";
select count(distinct NAME)
into :TOT
from SASHELP.VCOLUMN
where LIBNAME="WORK" and MEMNAME="ABC";
quit;
data want;
set have;
array to_process{&TO_PROCESS.} $20. (&LIST.);
array done{&TO_PROCESS.} 8.;
do I=1 to &TO_PROCESS.;
select(to_process{I});
when ('a') done{I}=1;
when ('b') done{I}=0;
otherwise;
end;
end;
run;
Note that this will give you a series of variables DONEx, having the numeric suffix after variable names is easier to deal with when talking about processing multiple columns (i.e. your example would be far easier if your variables were ORIG_VAR_x, then you would just define a range.
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.