Skip to content

Instantly share code, notes, and snippets.

@nicolashohm
Created October 8, 2024 14:06
Show Gist options
  • Save nicolashohm/5012ad9c3a178674b0060e0f10e19237 to your computer and use it in GitHub Desktop.
Save nicolashohm/5012ad9c3a178674b0060e0f10e19237 to your computer and use it in GitHub Desktop.
A macro to convert one more multiple variables from character to numeric
/**
* Converts one more multiple variables from character to numeric
*
* https://communities.sas.com/t5/SAS-Programming/Efficient-Way-to-Convert-Categorical-Text-Fields-to-Numeric-with/td-p/946374
*
* @param vars Variables to convert
* @param parse_format Format to translate the string to numbers
* @param format Format for the numeric field
*/
%macro recode(vars, parse_format, format);
%local i n var;
%let n = %sysfunc(countw(&vars, %str( )));
%do i = 1 %to &n;
%let var = %scan(&vars, &i, %str( ));
_&var = input(&var, &parse_format);
%end;
drop &vars;
%do i = 1 %to &n;
%let var = %scan(&vars, &i, %str( ));
rename _&var = &var;
format _&var &format;
%end;
%mend recode;
/*** Example Usage ***/
data mydata;
input id $ foo $ bar $;
datalines;
a yes No
d No Typo
f no Yes
;
run;
proc format;
invalue parse_yes_no (upcase)
'YES' = 1
'NO' = 0
' ','.' = .
other = _error_;
value yes_no
1 = 'Yes'
0 = 'No';
run;
data mydata_recoded;
set mydata;
%recode(foo bar, parse_yes_no., yes_no.);
/* Macro generates this code: */
*_foo = input(foo, parse_yes_no.);
*_bar = input(bar, parse_yes_no.);
*drop foo bar;
*rename _foo = foo;
*format _foo yes_no.;
*rename _bar = bar;
*format _bar yes_no.;
run;
@nicolashohm
Copy link
Author

Here, an example how to dynamically build the list of vars and call the macro:

data _null_;
set mydata;
	array char_vars _character_;
	length vars_to_recode $200; *Make sure 200 is enough for the amount of vars you have;
	vars_to_recode = '';
	
	do i = 1 to dim(char_vars);
	    varname = vname(char_vars[i]);
	   	if varname = 'id' or varname = 'description' then continue; *This if decides which variables are excluded;
	   	vars_to_recode = catx(' ', vars_to_recode, varname);
	end;
	call symputx('vars_to_recode', vars_to_recode);
run;

data mydata_recoded;
set mydata;
%recode(&vars_to_recode, parse_yes_no., yes_no.);
run;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment