BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
Ronein
Meteorite | Level 14

Hello

What is the reason that in data set "Have2"  the new variable X_new have length 1 and not 3 as in the original variable?

data have;
input X $;
cards;
MAX
MAX
VISA
DINERS
MAX
;
Run;

data have2 ;
set have;
IF _n_<=2 then X_new='';else X_new=X;
Run;

 

 

 

1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

Because in the first occurence in your code you give it a length of 1:

IF _n_<=2 then X_new='';else X_new=X;

The data step compiler takes the length from this first occurence to define the variable in the PDV.

Bottom line: to set a length for a variable, always use one of the explicit methods (LENGTH or ATTRIB statement) instead of implicit methods like you did here.

View solution in original post

4 REPLIES 4
Kurt_Bremser
Super User

Because in the first occurence in your code you give it a length of 1:

IF _n_<=2 then X_new='';else X_new=X;

The data step compiler takes the length from this first occurence to define the variable in the PDV.

Bottom line: to set a length for a variable, always use one of the explicit methods (LENGTH or ATTRIB statement) instead of implicit methods like you did here.

Ronein
Meteorite | Level 14
So better always to define length of a new variable and not let SAS decide for me....
Tom
Super User Tom
Super User

@Ronein wrote:
So better always to define length of a new variable and not let SAS decide for me....

If you KNOW the length it should have then yes be explicit.  The programmer that has to fix your code (which is usually you) will appreciate it.

 

If you want to make the code mimic an existing variable then you could easily re-write your logic so the compiler sees the simple copy of the old variable as the first place the new variable is referenced.

data have2 ;
  set have;
  X_new=X;
  if _n_<=2 then X_new=' ';
run;

And if you use CALL MISSING() it will work whether X is numeric or character.

data have2 ;
  set have;
  X_new=X;
  if _n_<=2 then call missing(X_new);
run;

If you want it to inherit the format, label and other attributes then you could get even trickier.

data have2 ;
  set have;
  set have(keep=x rename=(x=X_new));
  if _n_<=2 then call missing(X_new);
run;

sas-innovate-white.png

Missed SAS Innovate in Orlando?

Catch the best of SAS Innovate 2025 — anytime, anywhere. Stream powerful keynotes, real-world demos, and game-changing insights from the world’s leading data and AI minds.

 

Register now

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 882 views
  • 3 likes
  • 3 in conversation