5

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?

Feng Jiang
  • 1,776
  • 19
  • 25

2 Answers2

7

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;
Reeza
  • 20,510
  • 4
  • 21
  • 38
  • Note that this is true with *any* initial length of `x` - nothing special about 20. No matter what the length is, you always will have a 'full' variable (entirely padded with spaces). – Joe Dec 19 '14 at 15:59
  • 1
    May also be worth mentioning that there are other 'cat' functions as well... such as `cat()`, `catx()`, `cats()`, `catt()`, and `catq()`. And usually these are better options than the `||` or `!!` operators... – Robert Penridge Dec 19 '14 at 16:47
1

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).

sassy
  • 11
  • 1