Hi Everyone:
I have a data set that looks like this:
ABC INVESTMENT TR CO TR
ABC WORLD CO TRANSPORTATION
ABC SKYE INVESTMENT TR
ABC CLOUD PROPERTY TR
ABC MOVIES PRODUCTION TRUSTME
TRUST YOURSELF TR TRUE TRACTOR
Strings vary in length. My goal is to replace "TR" at the end of the string with "TRUST". I want to do this if and only if the last word is TR. Ideally, the data will look like this:
ABC INVESTMENT TR CO TRUST
ABC WORLD CO TRANSPORTATION
ABC SKYE INVESTMENT TRUST
ABC CLOUD PROPERTY TRUST
ABC MOVIES PRODUCTION TRUSTME
TRUST YOURSELF TR TRUE TRACTOR
I used tranwrd successfully to replace other parts of the strings, but got stuck on the last one. Could you help me with this? I am using SAS 9.4.
Thank you so much!
One way that uses the fact this is the LAST "word".
data example; length x $ 100; x="ABC INVESTMENT TR CO TR"; if scan(x,countw(x))='TR' then x=cats(x,'UST'); run;
Potential issue. If your current variable length is such that adding 3 characters would exceed the length of the variable then the value would be truncated.
data example; length x $ 25; x="ABC INVESTMENT TR CO TR"; if scan(x,countw(x))='TR' then x=cats(x,'UST'); run;
So you may have to create a new variable with a longer defined length.
One way that uses the fact this is the LAST "word".
data example; length x $ 100; x="ABC INVESTMENT TR CO TR"; if scan(x,countw(x))='TR' then x=cats(x,'UST'); run;
Potential issue. If your current variable length is such that adding 3 characters would exceed the length of the variable then the value would be truncated.
data example; length x $ 25; x="ABC INVESTMENT TR CO TR"; if scan(x,countw(x))='TR' then x=cats(x,'UST'); run;
So you may have to create a new variable with a longer defined length.
Just changing it at the end of the lines make it easy. You can just append something to the end of the string and to the end of the string you are asking TRANWRD() to change.
data want;
set have;
if scan(string,-1,' ')='TR' then do;
string=tranwrd(cats(string,'^%|'),'TR^%|','TRUST');
end;
run;
Otherwise learn how to use the regular expression functions.
Just for some fun .
data example;
length x $ 100;
x="ABC INVESTMENT TR CO TR";
y=prxchange('s/\btr$/TRUST/i',1,strip(x));
output;
x="ABC WORLD CO TRANSPORTATION";
y=prxchange('s/\btr$/TRUST/i',1,strip(x));
output;
run;
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.