DATA Step, Macro, Functions and more

How to remove numbers from charater variable

Accepted Solution Solved
Reply
Super Contributor
Posts: 297
Accepted Solution

How to remove numbers from charater variable

Hello, all:

 

I would like to remove the last number from the ID column.  I have 300 ID names which need to do this repeatly.  Please let me know how, thanks.

 

data state;

input ID $;

cards;

TN1

TN2

TN3

UCH1

UCH2

UCH3

UCH4

UCH5

ICFG1

ICFG2

ICFG3

ICFG4

ICFG5

ICFG6

;

run;


Accepted Solutions
Solution
‎06-05-2017 03:42 PM
PROC Star
Posts: 7,356

Re: How to remove numbers from charater variable

find a digit, searching from right to left. And, as I think about it, the code I suggested should actually have been:

data want;
  set state;
  if findc(id,,'db') eq length(id) then id=substr(id,1,findc(id,,'db')-1);
run;

i.e., only remove the last character .. if it is a digit.

 

Art, CEO, AnalystFinder.com

 

View solution in original post


All Replies
Trusted Advisor
Posts: 1,354

Re: How to remove numbers from charater variable

[ Edited ]

There are several ways to remove the numbers:

data state;
input ID $;
/*1*/ id = translate(id,'','0123456789');
/*2*/ id = compress(id,'0123456789');
/*3*/ id = compress(id,' ','D'); cards; ... your data ... run;
Super User
Super User
Posts: 7,392

Re: How to remove numbers from charater variable

You could also do:

id = compress(id,,'ka');

K=Keep, A=Alpha.

http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a000212246.htm

 

Might be a bit shorted if you had other things as there are a few options in compress.

Trusted Advisor
Posts: 1,128

Re: How to remove numbers from charater variable

[ Edited ]
data state;
input ID $;
new=prxchange('s/\d$/ /',-1,strip(id));
cards;
TN1
TN2
TN3
UCH1
UCH2
UCH3
UCH4
UCH5
ICFG1
ICFG2
ICFG3
ICFG4
ICFG5
ICFG6
;
run;
Thanks,
Jag
PROC Star
Posts: 7,356

Re: How to remove numbers from charater variable

If you only want to remove one digit if it exists at the end of an id you could use:

data want;
  set state;
  if findc(id,,'db') then id=substr(id,1,findc(id,,'db')-1);
run;

Art, CEO, AnalystFinder.com

 

Super Contributor
Posts: 297

Re: How to remove numbers from charater variable

What is the 'db' refering?

Solution
‎06-05-2017 03:42 PM
PROC Star
Posts: 7,356

Re: How to remove numbers from charater variable

find a digit, searching from right to left. And, as I think about it, the code I suggested should actually have been:

data want;
  set state;
  if findc(id,,'db') eq length(id) then id=substr(id,1,findc(id,,'db')-1);
run;

i.e., only remove the last character .. if it is a digit.

 

Art, CEO, AnalystFinder.com

 

Super Contributor
Posts: 297

Re: How to remove numbers from charater variable

Thanks for your kind help.

☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 7 replies
  • 140 views
  • 5 likes
  • 5 in conversation