Usage Note 22218: How do I convert a SAS data set that contains all numeric data in character variables to a SAS data set that has numeric variables containing the numeric data with the same variable names?
This macro changes all the character variables within a SAS data set to numeric.
This macro can also be easily modified to do the opposite of the above. To have all numeric variables changed to character just make the changes described within the two comments in the code below.
/** Sample dataset **/
data one;
input @1 a @3 b $10. @14 c $5. @20 d;
cards;
1 2654321234 33456 4
;
%macro vars(dsn);
/* initialize these two variables */
%let list=;
%let type=;
/* open the data set */
%let dsid=%sysfunc(open(&dsn));
/* obtain number of variables in the data set and put into &CNT */
%let cnt=%sysfunc(attrn(&dsid,nvars));
/* put all variable names into &LIST and a C or N for each variable into &TYPE to represent if the */
/* the associated variable is character or numeric */
%do i = 1 %to &cnt;
%let list=&list %sysfunc(varname(&dsid,&i));
%let type=&type %sysfunc(vartype(&dsid,&i));
%end;
/* close the data set */
%let rc=%sysfunc(close(&dsid));
/* construct the DROP= option to remove the new variables that are created during the step */
data two(drop=
%do i = 1 %to &cnt;
%let temp=%scan(&list,&i);
_&temp
%end;);
/* rename the current variables to those prefixed with an underscore */
set &dsn(rename=(
%do i = 1 %to &cnt;
%let temp=%scan(&list,&i);
&temp=_&temp
%end;));
%do j = 1 %to &cnt;
%let temp=%scan(&list,&j);
/** Change C to N for numeric to character conversion **/
%if %scan(&type,&j) = C %then %do;
/** Also change INPUT to PUT for numeric to character **/
&temp=input(_&temp,8.);
%end;
%else %do;
&temp=_&temp;
%end;
%end;
run;
%mend vars;
/* invoke the macro */
%vars(one)
/** Verify conversion has been made **/
proc contents data=two;
run;
Operating System and Release Information
*
For software releases that are not yet generally available, the Fixed
Release is the software release in which the problem is planned to be
fixed.
Type: | Usage Note |
Priority: | low |
Topic: | SAS Reference ==> Macro SAS Reference ==> Functions ==> Special ==> INPUT
|
Date Modified: | 2007-10-24 12:55:37 |
Date Created: | 2002-12-16 10:56:48 |