DATA Step, Macro, Functions and more

Trying to get the first three characters of firstname

Reply
Frequent Contributor
Posts: 104

Trying to get the first three characters of firstname

Doing this brought in the last three chars of the first name, but I need to know what to do to get the first three chars:

 

  ***DEFINE ABBREVIATED NAME FOR MERGE***;              
 DATA ENROLL2;                                          
  SET ENROLL.DATA;                                      
      **REMOVE SPACES AND PUNCTUATION**;                
   NAMECOMP=COMPRESS(FIRSTNAME,,'PS');                  
  ***FIRST THREE CHARS, OR WHOLE NAME IF SHORTER**;     
  NAME3=SUBSTR(NAMECOMP,MIN(3,LENGTH(NAMECOMP)));       
  RUN;                                                  
                                                        
  DATA BENE2;                                           
    SET BENES.DATA;                                     
  **REMOVE SPACES AND PUNCTUATION**;                    
  NAMECOMP=COMPRESS(FIRST_NAME,,'PS');                  
  ***FIRST THREE CHARS, OR WHOLE NAME IF SHORTER**;     
  NAME3=SUBSTR(NAMECOMP,MIN(3,LENGTH(NAMECOMP)));       
  RUN;                                                  

 

 

Any help is appreciated.

Super Contributor
Super Contributor
Posts: 266

Re: Trying to get the first three characters of firstname

 

SUBSTR(SOURCE, POSITION, N)

 

The function returns N characters, beginning at character number POSITION from the string SOURCE.

 

namefirst3 = SUBSTR (NAMECOMP, 1, 3);   

.
 
Super User
Posts: 13,321

Re: Trying to get the first three characters of firstname

First three would be SUBSTR(variablename, 1,3);

 

the first parameter to substr is the START position, the second is length.

If the variable is shorter than 3 you'll get what's there.

 

NAME3=SUBSTR(NAMECOMP,1,3);

 

when you used

NAME3=SUBSTR(NAMECOMP,MIN(3,LENGTH(NAMECOMP)));       

your starting position was the smaller of 3 or the length of the namecomp variable value.

 

Super User
Posts: 6,632

Re: Trying to get the first three characters of firstname

Perhaps simpler:

 

length name3 $ 3;

name3 = namecomp;

 

Since the length is 3, there is only room to store the first 3 characters.

Ask a Question
Discussion stats
  • 3 replies
  • 152 views
  • 1 like
  • 4 in conversation