SAS Programming

DATA Step, Macro, Functions and more
BookmarkSubscribeRSS Feed
smg3141
Obsidian | Level 7

Hello,

 

I'm trying to add dashes in the middle of a string of social security numbers. For example, 123456789 -> 123-45-6789. 

 

I've been trying to use the cat and substr commands, but I don't think I'm totally understanding how the substr function works. I'm still new to SAS. 

 

data want;
set have;
length ssn_dash $11;
ssn_dash = ssn;
ssn_dash = cat(substr(ssn_dash,1,3), '-', substr(ssn_dash,3));
ssn_dash = cat(substr(ssn_dash,1,6), '-', substr(ssn_dash,6));
run;

 

Any advice would be greatly appreciated!

3 REPLIES 3
PGStats
Opal | Level 21

Assuming ssn is a character string variable:

 

ssn_dash = catx("-", substr(ssn,1,3), substr(ssn,4,2), substr(ssn,6));

PG
jimbarbour
Meteorite | Level 14

You were very close.  The only adjustment that you would need would be to do add 1 to the last argument of your second substring on each line:

jimbarbour_0-1600310827891.png

Then you get just what you were after:

jimbarbour_2-1600310893519.png

 

However, that said, I think it's typically better to just do it all in one line as @PGStats suggests.  Notice also that he/she uses CATX instead of just CAT.  The CATX function puts a value in between each of the subsequent specified values so that you don't have to code '-' multiple times.  Nice function to know about.  I also find CATS to be useful.  CATS is the about the same as CAT except that it executes a STRIP function on each term.  CATS would be like coding CAT(STRIP(Var1), STRIP(Var2), STRIP(Var3)).  Very useful in my opinion.

 

Jim

 

 

Ksharp
Super User
data _null_;
x=123456789;
y=put(x,ssn.);
put x= / y=;
run;

sas-innovate-white.png

Special offer for SAS Communities members

Save $250 on SAS Innovate and get a free advance copy of the new SAS For Dummies book! Use the code "SASforDummies" to register. Don't miss out, May 6-9, in Orlando, Florida.

 

View the full agenda.

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 5004 views
  • 3 likes
  • 4 in conversation