Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why SAS string concat cannot involve the variable itself?

Tags:

sas

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?

like image 784
Feng Jiang Avatar asked Dec 19 '14 02:12

Feng Jiang


2 Answers

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;
like image 153
Reeza Avatar answered Sep 28 '22 11:09

Reeza


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

like image 44
sassy Avatar answered Sep 28 '22 13:09

sassy