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-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 4 replies
  • 888 views
  • 0 likes
  • 3 in conversation