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
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.