Help using Base SAS procedures

counter

Reply
Occasional Contributor
Posts: 15

counter

I wonder how can I add variable' obs', which basically is a counter of observation. Below code is not efficient (it is slow to run), plus in case I don't know the total number of observations, what should I  put in place of '9'. ?

Thank you

Telescopic

-----------------------------------------------------

data test;

   input Year Month Total;

cards;

2009 4 16

2009 5 18

2009 6 12

2009 7 15

2009 8 11

2009 9 12

2009 10 7

2009 11 6

2009 12 9

;

DO i=1 to 9;

num_obs=i;

output;

end;

drop i;

run;

proc print data=test;

run;

Super User
Super User
Posts: 6,502

counter

SAS will increment the special variable _N_ for every time it loops through the data step.  So replace your lines in red with the statement:

OBS = _n_;

PROC Star
Posts: 7,363

counter

Tom already answered your question, other than there is no reason to change your variable name (i.e., num_obs=_n_ will also work).  So would num_obs+1 in place of the lines in red.

But I'm concerned that the code you tried "too so long".  It wouldn't give you the expected result as it would loop through each case nine times and result with num_obs always equaling 9, but should have run in a fraction of a second and produced 81 records.

Art

Super Contributor
Posts: 264

Re: counter

Do you need the total number of observations in an additional variable in each observation or do you need the observations position in the dataset?

The variables nlobs and nobs in sashelp.vtable contain the total number of observations in a dataset.

/* get number of obs */

proc sql;

    select nlobs into :counter

    from sashelp.vtables

    where lowcase(libname) = 'work' and lowcase(memname) = 'test';

quit;

/* update dataset */

data work.test;

    set work.test;

    num_obs = &counter;

run;

Code is not tested!

Occasional Contributor
Posts: 15

Re: counter

Thank you all. The Do-loop was wrong. I finally do the following.

----------------------------

data test;
   input Year Month Total;

cards;
2009 4 16
2009 5 18
2009 6 12
2009 7 15
2009 8 11
2009 9 12
2009 10 7
2009 11 6
2009 12 9
;
run;

data test_1;
set test;
/*retain counter 0;                           /*alternative*/
counter=counter+1;*/
OBS=_n_;
RUN;

proc print data=test_1;
run;

Frequent Contributor
Posts: 104

Re: counter

Only one data step is needed.

data test;
   input Year Month Total;

   obs = _n_;

cards;
2009 4 16
2009 5 18
2009 6 12
2009 7 15
2009 8 11
2009 9 12
2009 10 7
2009 11 6
2009 12 9
;

proc print;
run;

Ask a Question
Discussion stats
  • 5 replies
  • 236 views
  • 6 likes
  • 5 in conversation