DATA Step, Macro, Functions and more

_N_ to character

Frequent Contributor
Frequent Contributor
Posts: 133

_N_ to character

Why am I getting this error message? I need to create a new ID based on the _N_ observation variable. and I'd like the new variable to be a character variable. Is there a cleaner way to do this without the error message?


2300 data dataprep.comboIdentifier ;
2301 format UniqueID $3. ;
2302 set dataprep.comboIdentifier ;
2303 UniqueID=put(_N_,$3.) ;
WARNING: Variable _N_ has already been defined as numeric.
2304 run;


Posts: 551

Re: _N_ to character

[ Edited ]

Like this? Smiley Happy


/* Test Data Set */
data have;
   do i = 1 to 10;

/* Use CATS function on _N_ to convert to character variable */
data want;
   length N $8.;
   set have;
   N = cats(_N_);

/* Use PROC CONTENTS to verify that N is a character Variable */
proc contents data = want;run;


Posts: 172

Re: _N_ to character

[ Edited ]

Reason: _N_ is numeric variable and your $3. is character format ,So they are not matched

Try something like this:

data want1;
set sashelp.class;
id=left(_n_); /*or this*/
UniqueID=put(_N_,3.) ;/*remove the $ in the format*/



Naveen Srinivasan

Super User
Posts: 5,083

Re: _N_ to character

You might find it easier to work with if you insert leading zeros:


Unique_ID = put(_n_, z3.);

Super User
Super User
Posts: 6,500

Re: _N_ to character

Your use of formats is a little confused. You need to use a numeric format with a numeric value like _N_.  Also you are using a FORMAT statement where you probably meant to use a LENGTH or ATTRIB statement to define your new varaible. There is normally no need to attached $nn. formats to character varaibles.  You probably do not want to have leading spaces in your new character variable.  Also if you want your new character variable to sort in the same order as the original integer values then you should use the Z. format so that the smaller values will have leading zeros.


data dataprep.comboIdentifier ;
  length UniqueID $3 ;
  set dataprep.comboIdentifier ;
  UniqueID=put(_N_,Z3.) ;
Ask a Question
Discussion stats
  • 4 replies
  • 1 like
  • 5 in conversation