DATA Step, Macro, Functions and more

Why the TRANSLATE FUNCTION translate incorrectly?

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 12
Accepted Solution

Why the TRANSLATE FUNCTION translate incorrectly?

Hi everyone:

I've written the code as below and I expected the result in log was '123456789101112;223456789101112' but what I get is '323;223'. Would anyone tell me why the TANSLATE did not work as is described and how to approach what I want? Appreciate any help!

The code:

data _null_;

length tran $50.;

tran=translate('yhp;qly','123456789101112','yhp','223456789101112','qly');

put tran;

run;

Qinly


Accepted Solutions
Solution
‎01-15-2015 07:37 PM
Super User
Super User
Posts: 7,039

Re: Why the TRANSLATE FUNCTION translate incorrectly?

Posted in reply to LinyuanQin

Looks like it is doing what you asked.  TRANSLATE works on characters, not strings.

You told it to take the string

'yhp;qly'


And make these letter transformations:

y -> 1

h -> 2

p -> 3

q -> 2

l -> 2

y -> 3


Note that have two different targets for the letter y so the last one won and you ended up with:

'323;223'


Perhaps you wanted to use TRANWRD() or TRANSTRN() function instead?



View solution in original post


All Replies
Super User
Super User
Posts: 7,942

Re: Why the TRANSLATE FUNCTION translate incorrectly?

Posted in reply to LinyuanQin

Hi,

Check out the help documentation for the function: http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a000215153.htm

Firstly the details section explains why the length is not as expected - it sets the new variable to be as long as the first parameter you pass in, so yhp;qly = length 7, output length is going to be 7, not all those other characters.

Also, you may want to split that statement up:

data tmp;

length tran $50.;

tran=translate('yhp;qly','123456789101112','yhp');
tran=translate(tran,'223456789101112','qly');
put tran;

run;

Or, use the tranwrd function just to replace things.

Solution
‎01-15-2015 07:37 PM
Super User
Super User
Posts: 7,039

Re: Why the TRANSLATE FUNCTION translate incorrectly?

Posted in reply to LinyuanQin

Looks like it is doing what you asked.  TRANSLATE works on characters, not strings.

You told it to take the string

'yhp;qly'


And make these letter transformations:

y -> 1

h -> 2

p -> 3

q -> 2

l -> 2

y -> 3


Note that have two different targets for the letter y so the last one won and you ended up with:

'323;223'


Perhaps you wanted to use TRANWRD() or TRANSTRN() function instead?



🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 2 replies
  • 237 views
  • 3 likes
  • 3 in conversation