Feng Jiang
Feng Jiang

Reputation: 1945

Why SAS string concat cannot involve the variable itself?

This issue drives me crazy. In SAS, when I want to concat a string, the variable which will be assigned to the result cannot be used in the input.

DATA test1;
    LENGTH x $20;
    x = "a";
    x = x || "b";
RUN;

Result: x = "a";

DATA test2;
    LENGTH x $20;
    y = "a";
    x = y || "b";
RUN;

Result: x = "ab";

DATA test3;
    LENGTH x $20;
    x = "a";
    y = x;
    x = y || "b";
RUN;

Result: x = "a";

The last one is so strange. x is not even involved in concat directly.

This does not make sense. Because 1) you can do other operations in this way, e.g. transtrn, substr. 2) SAS does not give any warning message.

Why?

Upvotes: 5

Views: 2179

Answers (2)

sassy
sassy

Reputation: 11

You could also use substr() on the left hand side of the equation. Something like:

substr(x,10,1) = 'a';

to set the 10th car to 'a'. Then loop over each character in x (where the 10 is).

Upvotes: 1

Reeza
Reeza

Reputation: 21264

It's because the length of X is initially set 20, so it has 19 trailing blanks. If you add b, there isn't room for it, because of the trailing blanks. Either trim the x before cat operator or use catt. You can use lengthc to see the length of the character variable.

DATA test1;
    LENGTH x $20;
    x = "a";
    len=lengthc(x);
    x = trim(x) || "b";
   *x = catt(x, b);
RUN;

proc print data=test1;
run;

Upvotes: 7

Related Questions