SAS Loop

Reply
Regular Contributor
Posts: 150

SAS Loop

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!

Regular Contributor
Posts: 216

Re: SAS Loop

Posted in reply to rfarmenta

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;

Super User
Posts: 11,343

Re: SAS Loop

Posted in reply to rfarmenta

If EpiInfo will export to CSV you may have better luck. Or you can try changing the data type in Excel to numeric

Contributor
Posts: 69

Re: SAS Loop

Posted in reply to rfarmenta

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

Ask a Question
Discussion stats
  • 3 replies
  • 227 views
  • 0 likes
  • 4 in conversation