SAS OnlineTutor HomeFAQ PageSuggested Learning PathsContents+Search||next

Transforming Data with SAS Functions
Modifying Character Values with Functions

 
Now let's use the SUBSTR function to replace the 622 exchange in the variable Phone. You begin by writing this assignment statement:
     data hrd.temp2;
        set hrd.temp;
        substr(phone,1,3)='433';
     run;

SAS Data Set Hrd.Temp
City State Zip Phone BeginDate EndDate PayRate Days Hours
CARY NC 27513 6224549 14567 14621 10 11 88
CARY NC 27513 6223251 14524 14565 8 25 200
CHAPEL HILL NC 27514 9974749 14570 14608 40 26 208


This statement specifies that the new exchange 433 should be placed in the variable Phone, starting at character position 1 and replacing three characters.
     data hrd.temp2;
        set hrd.temp;
        substr(phone,1,3)='433';
     run;

But executing this DATA step places the value 433 into all values of Phone. You only need to replace the values of Phone containing the exchange 622. So, you include a second assignment statement in the DATA step to extract the exchange from Phone.

     data hrd.temp2(drop=exchange);
        set hrd.temp;
        Exchange=substr(phone,1,3);
        substr(phone,1,3)='433';
     run;

Notice that the SUBSTR function appears on the right side of the assignment statement to extract a substring from Phone. This DATA step also needs an IF-THEN statement to verify the value of the variable Exchange. If the exchange is 622, the assignment statement executes to replace the value of Phone.

     data hrd.temp2(drop=exchange);
        set hrd.temp;
        Exchange=substr(phone,1,3);
        if exchange='622' then substr(phone,1,3)='433';
     run;

After the DATA step is executed, the appropriate values of Phone contain the new exchange.


SAS Data Set Hrd.Temp2
City State Zip Phone BeginDate EndDate PayRate Days Hours
CARY NC 27513 4334549 14567 14621 10 11 88
CARY NC 27513 4333251 14524 14565 8 25 200
CHAPEL HILL NC 27514 9974749 14570 14608 40 26 208


Once again, remember the rules for using the SUBSTR function. If the SUBSTR function appears on the right side of an assignment statement, the function extracts a substring.
     MiddleInitial=substr(middlename,1,1);

If the SUBSTR function appears on the left side of an assignment statement, the function replaces the contents of a character variable.

     substr(region,1,3)='NNW';

|next


Copyright © 2002 SAS Institute Inc., Cary, NC, USA. All rights reserved.

Terms of Use & Legal Information | Privacy Statement