DATA Step, Macro, Functions and more

Replacing entries

Reply
Frequent Contributor
Posts: 77

Replacing entries

Hello,

 

I have a dataset with a variable that is suppose to only be numeric from 1 through 4, but has some extra variables like A B C and D. I am trying to change those alphabetical variables to the following:

 

A = 1; B = 2; C = 3; D = 4;

 

What exactly is the sas code for this? Here's a sample dataset Thank you.

 

data CDC.SAMPLEEDUCATION;
  infile datalines dsd truncover;
  input Education_Level:$1.;
datalines4;
1
2
3
4
1
2
3
4
1
4
A
B
C
D
;;;;
Super User
Posts: 5,260

Re: Replacing entries

There are many ways. The translate function, the case statement in SQL, to name a few.
Data never sleeps
PROC Star
Posts: 290

Re: Replacing entries

A custom informat would do what you want directly in the data step:

 

proc format;
    invalue fixMe
        'A' = 1
        'B' = 2
        'C' = 3
        'D' = 4
        OTHER = [best.];
run;
 

data  SAMPLEEDUCATION;
  infile datalines dsd truncover;
  input Education_Level :fixMe.;
datalines4;
1
2
3
4
1
2
3
4
1
4
A
B
C
D
;;;;
Valued Guide
Posts: 505

Re: Replacing entries



If A=1,B=2 -- Z=26 and you character code is ascii

data SAMPLEEDUCATION;
  input Education_Level $1.;
  if anyalpha(education_level) then num=rank(Education_Level) -64;
  else num=input(Education_Level,1.);
cards4;
1
2
3
4
1
2
3
4
1
4
A
B
C
D
;;;;
run;quit;


Up to 40 obs WORK.SAMPLEEDUCATION total obs=14

       EDUCATION_
Obs      LEVEL       NUM

  1        1          1
  2        2          2
  3        3          3
  4        4          4
  5        1          1
  6        2          2
  7        3          3
  8        4          4
  9        1          1
 10        4          4
 11        A          1
 12        B          2
 13        C          3
 14        D          4



Ask a Question
Discussion stats
  • 3 replies
  • 214 views
  • 5 likes
  • 4 in conversation