Help using Base SAS procedures

auto id

Accepted Solution Solved
Reply
Regular Contributor
Posts: 192
Accepted Solution

auto id

Hello,

 

How do I create a new variable named 'Count' that starts at 1 on row 1 and increases by 1 increment through the last observation?

 

Is it possible to do this using proc sql?  Or is it better to do it using the data stet?

 

 

Thanks!


Accepted Solutions
Solution
‎03-03-2017 06:13 PM
PROC Star
Posts: 7,364

Re: auto id

Of course! Just add a retain statement before the set statement. E.g.,:

 

data want;
  retain count;
  set sashelp.class;
  count=_n_;
run;

Art, CEO, AnalystFinder.com

 

View solution in original post


All Replies
PROC Star
Posts: 7,364

Re: auto id

There is already an automatic variable that does that. You just have to capture it in a data step. e.g.:

 

data want;
  set sashelp.class;
  count=_n_;
run;

Art, CEO, AnalystFinder.com

Regular Contributor
Posts: 192

Re: auto id

This works!  Is there a way to get this as the first column in the output?  Right now, it is the last.

Solution
‎03-03-2017 06:13 PM
PROC Star
Posts: 7,364

Re: auto id

Of course! Just add a retain statement before the set statement. E.g.,:

 

data want;
  retain count;
  set sashelp.class;
  count=_n_;
run;

Art, CEO, AnalystFinder.com

 

Regular Contributor
Posts: 192

Re: auto id

Thank you!

Super User
Super User
Posts: 7,413

Re: auto id

The question would be why.  It sounds like your coming from SQL to SAS and there is an understanding gap between the two.  SQL does not assume sorted data - in fact apart from grouping and ordering, data can go in any way - hence why there are functions to create these types of ID field either automatically or by hand.  In SAS however it is different, the basic functionality expects sorted data - i.e. by group processing (there is the unsorted option - however that doesn't mean the data is not sorted, just not logically).  So as your data will always be in group by order for any processing, and id field should not be necessary, and if it is needed for some logic then you can just use _n_.

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 5 replies
  • 210 views
  • 1 like
  • 3 in conversation