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
if you are creating three separate variables, this should work..
third=Compress(substr(Road_No ,1,2)||'B'||substr(Road_No ,4,4));
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.
Need further help from the community? Please ask a new question.