BookmarkSubscribeRSS Feed
Aexor
Lapis Lazuli | Level 10

Could you please explain below code  ;

data xyz;
input x $;
cards;
AA
AA
AA
BB
BB
;
run;

 

data A;
set xyz;
by x;
if first.x then
N+1;
run;

output :- 

Obs x N
1 AA 1
2 AA 1
3 AA 1
4 BB 2
5 BB  2

 


data B;
set xyz;
by x;
if first.x then N=1;
else N+1;
run;

 

output for B is

Obs x N
1 AA 1
2 AA  2
3 AA  3
4 BB  1
5 BB 2

 

I know how dateset B is created its the incrementing the value based of the occurrence of by group x but not sure how dataset A is being created .

Please explain.

1 REPLY 1
Kurt_Bremser
Super User

The SUM statement

N + 1;

implies an automatic RETAIN of the variable.

In dataset A, the increment happens only when a new group starts; when this happens the first time (and N is still missing), N is set to 1 (like it happens with missing values in a SUM function).

SAS Innovate 2025: Call for Content

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 16. Read more here about why you should contribute and what is in it for you!

Submit your idea!

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 1 reply
  • 375 views
  • 0 likes
  • 2 in conversation