BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
jylo
Calcite | Level 5

I'm trying to write to conditionally substitute portions of a text string. For example, if I have:

A123

AX345

B456

BY789

 

I want the values in my data set to be:

AX123

AX345

BY456

BY789

 

Is there a way to accomplish this in one prxchange statement?

(Using SAS 9.4.)

1 ACCEPTED SOLUTION

Accepted Solutions
Ksharp
Super User
data have;
input x $ y $;
length want pid $ 40;
pid=cats('s/^([a-z])[a-z]*(\d+)/$1',y,'$2/i');
want=prxchange(pid,1,x);
cards;
A123 X
AX345 X
B456 Y
BY789 Y
;
run;

View solution in original post

4 REPLIES 4
Ksharp
Super User
Assuming the data is just like what you posted:


data have;
input x $20.;
cards;
A123
AX345
B456
BY789
;
run;
data have;
 set have;
 group=first(x);
 n=length(x);
run;
proc sort data=have;
 by group n;
run;
data want;
 do until(last.group);
  set have;
  by group;
 end;
 _x=x;
 do until(last.group);
  set have;
  by group;
  x=scan(_x,1,,'d')||scan(x,-1,,'kd');
  output;
 end;
 drop _x group n;
run;

RW9
Diamond | Level 26 RW9
Diamond | Level 26

Depends on several factors, is it just two, then:

data have;
  input x $20.;
cards;
A123
AX345
B456
BY789
;
run;
data want;
  set have;
  x=ifc(substr(x,1,1)="A",cats("AX",compress(x," ","kd")),cats("BY",compress(x," ","kd")));
run;

If its more, but you know them up front then:

data want;
  set have;
  select(substr(x,1,1));
    when ("A") x=cats("AX",compress(x," ","kd"));
    when ("B") x=cats("BY",compress(x," ","kd"));
    otherwise;
  end;
run;

If you don't know them up front then you will need to provide the logic to populate them, I.e. you could have AX and AY?

jylo
Calcite | Level 5

The second alpha character is always known.

 

Is there a way to do this using PRXCHANGE?

Ksharp
Super User
data have;
input x $ y $;
length want pid $ 40;
pid=cats('s/^([a-z])[a-z]*(\d+)/$1',y,'$2/i');
want=prxchange(pid,1,x);
cards;
A123 X
AX345 X
B456 Y
BY789 Y
;
run;

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

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
  • 4 replies
  • 1501 views
  • 0 likes
  • 3 in conversation