We are using EpiInfo to manage our lab data for one of our studies. Because of the way we had to set up our data entry forms in EpiInfo when I export data out of EpiInfo into excel to read into SAS, all of the variables are character variables, even if it is a numeric value.
How do I create a loop in SAS that will convert all of the variables that I want to from Character to Numeric so I don't have to do it manually in Excel. Any help would be greatly appreciated!
Try this,
data chars;
length chr1 char2 char3 $8;
chr1='23' ; char2='45' ; char3='78' ; output;
chr1='44' ; char2='66' ; char3='99' ; output;
chr1='11' ; char2='22' ; char3='88' ; output;
run;
proc sql noprint;
select strip(put(count(*),best.))
into :g_numCount
from dictionary.columns
where libname='WORK'
and memname='CHARS'
and type='char'
;
quit;
%put &g_numCount;
data nums (keep=numvars1-numvars&g_numCount);
set chars;
array charvars (&g_numCount) $ _character_;
array numvars (&g_numCount) 8 numvars1 - numvars&g_numCount;
do i=1 to dim(numvars);
numvars=input(charvars,best8.);
end;
run;
If EpiInfo will export to CSV you may have better luck. Or you can try changing the data type in Excel to numeric
Both of these are good answers. Ballardw's though requires manipulation of the Excel worksheet... if you already open the file for maybe a quick visual review then this won't be too burdensome. You could even write a simple VB-Excel macro to change the format of the columns of interest.
If on the other hand you need a solution that requires no manual intervention and you want to convert all character variables to numeric and the number of character variables varies from file to file then Ahmed's approach is the better of the two
If the names and number of character variable doesn't change then here's an approach similar Ahmed's. It uses a LIBNAME statement to import the Excel file and loads the arrays with a hardcoded list of the character variables that need to be converted. Not tested.
libname xls excel '<drive>:/<path>/<filename>.xls';
data epinfo_data_with_numeric_vars;
set xls.<sheet_name>$'n;
array charvars {*} $ charvar1-charvar8;
array numvars {*} numvar1 - numvar8;
do i=1 to dim(numvars);
numvars=input(charvars,best.);
end;
drop charvar1-charvar8;
run;
Be sure to let us know which answer you accept.
John
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.