Hello All,
I am pretty new to SAS, looking forward for your advice.
I want to replace first letter and last letter in given set of observations.
Below are my questions.
Q1: I have a variable called Road_No and i have 5000 observations in that.
I would like to replace first letter of the observations with H. How do i do it. Road_No is character variable and length of the observations are 7.
Example: Road_No are A001010,BC01010,and so on, I want replace the first letter of A and B to H001010 ,HC01010
Q2: Same way how do i replace last digit with M.
Q3: How do i replace third digit. Example: HA01011 To HAB1011
Regards,
Bidd
Are you creating three different variables from one or you are only interested in replacing the first, third and last?
You can try this:
data want;
set have;
newval=Compress('H'||substr(Road_No ,2,1)||'B'||substr(Road_No ,4,4));
run;
Are you creating three different variables from one or you are only interested in replacing the first, third and last?
if you are creating three separate variables, this should work..
data want;
set have;
first=Compress('H'||substr(Road_No ,2,6));
second=Compress(substr(Road_No ,1,6)||'M');
third=Compress(substr(Road_No ,1,2)||'B'||substr(Road_No ,4,4));
run;
good luck
Try this...
data HAVe;
INPUT VALUE $7.;
CARDS;
A001010
B001010
C001010
D001010
;
run;
data WANT;
set HAVE;
value=ifc(substr(value,1,1) in ('A','B'), 'H'||substr(value,2), value); *replace 1st char if 'A' or 'B';
value = substr(value,1,6)||'M'; *REPLACE LAST CHAR;
value = substr(value,1,2)||'B'||substr(4,4); *REPLACE THIRD CHAR;
run;
Hope this helps.
There is a trick here which is useful to learn. The substr function can appear on the left of an equals sign. What this does is for the given substr command put the text from the right in, so you can do:
data want; set have; substr(road_no,1,1)="H"; substr(road_no,lengthn(road_no)-1,1)="M"; substr(road_no,3,1)="B"; run;
So what we do here is with the substr specify where the characters on the right should go in the string. In the second one I take the lengthn of the string and drop back one char to get the last char position.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.