I want to add serial number to the unique values of each group. See the snapshot below-
data xyz;
input x $;
cards;
AA
AA
AA
BB
BB
;
run;
proc sql;
select a.x, b.N from xyz a
inner join
(select x, monotonic() as N
from (
select distinct x
from xyz)) b
on a.x=b.x;
quit;
How we can do it with data step?
Close but no cigar:
data temp;
set xyz;
by x;
retain z 0;
if first.x then z+1;
run;
proc print;
run;
http://www.ats.ucla.edu/stat/sas/faq/enumerate.htm
Use BY group processing, see a detailed write up in the link above.
I have tried but didn't get any success.
data temp;
set xyz;
if first.x then z=1;
else z+1;
by x;
proc print;
run;
It increments the value. It's not my desired output.
Close but no cigar:
data temp;
set xyz;
by x;
retain z 0;
if first.x then z+1;
run;
proc print;
run;
Thanks a ton. It works like a charm. How it works? I failed to understand how it increments with "if first.x then z+1;" and how it keeps the same value to values of a same group?
RETAIN is a datastep instruction that says to keep the value of a variable from record to another. This will not typically work if the variable(s) named in the Retain statement exist in a data set on the SET statement as they would be read from the set.
Using a statement like:
Z+1; /* note there is no = in the assignment*/
implies that Z should be retained.
Thanks for your explanation. I am confused why ELSE statement was not required. See my code below-
data example22;
set xyz;
if first.x then N+1;
else N=N;
by x;
proc print;
run;
Because you wanted the same value of the counter for all records with the same value of x you don't want an Else. The retain keeps the value once assigned.
The ELSE clause would be for something you only want to do for records that are not the first.x.
See this thread for one example of Else with First.var processing to do something just a little more complicated that your problem:
BY group processing:
http://support.sas.com/documentation/cdl/en/lrcon/62955/HTML/default/viewer.htm#a001283274.htm
RETAIN
keeps the value from row to row
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.