Created
October 8, 2024 14:06
-
-
Save nicolashohm/5012ad9c3a178674b0060e0f10e19237 to your computer and use it in GitHub Desktop.
A macro to convert one more multiple variables from character to numeric
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here, an example how to dynamically build the list of vars and call the macro: