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;

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

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
  • 1592 views
  • 0 likes
  • 3 in conversation