Help using Base SAS procedures

how to recode a variable

Reply
Frequent Contributor
Posts: 75

how to recode a variable

Hello all-

suppose in my data set i have an id variable:

id
3
3
3
4
4
4
4
6
7
7

and i want to create a new id variable (in the same data set) say id2 such that now we have in the data set:

id id2
3 1
3 1
3 1
4 2
4 2
4 2
4 2
6 3
7 4
7 4

and so on. i need to be able to generalize this regardless of the numbers in the id column. in short i need to recode the id column starting from 1 on up.

Any way to do this?

Cheers
Geo
Super User
Posts: 19,837

Re: how to recode a variable

Look up BY Group processing and retain.

The following will work
data have;
input id;
cards;
3
3
3
4
4
4
4
6
7
7
;
run;

proc sort data=have;
by id;
run;

data want;
set have;
by id;
retain id2 0;
if first.id then id2+1;
run;
Frequent Contributor
Posts: 75

Re: how to recode a variable

Thanks!!
Regular Contributor
Posts: 241

Re: how to recode a variable

Just a minor reminder that the "accumulator" variable in the sum statement is automatically initialized to zero and retained. Thus the retain statement is not necessary. The fine manual even metions that a sum statement is equivalent to:
[pre]
retain variable 0;
varibale = sum(varible, expression);
[/pre]

Thus your data want step can be as simple as:
[pre]
data want;
set have;
by id;
id2 + first.id;
run;
[/pre]
Ask a Question
Discussion stats
  • 3 replies
  • 120 views
  • 0 likes
  • 3 in conversation