UCLA Academic Technology Services HomeServicesClassesContactJobs

SPSS Code Fragment
Generating id numbers within group or panel

The code below shows how to create an id variable that takes on the values 1 to n within each group/panel (where n is the number of cases in a group). The grouping variable is defined by the user. The number of cases, n, need not be the same across all groups. In the example dataset, group is the grouping variable. v1 and v2 are additional variables in the dataset, they are not modified by the code.


data list list /group v1 v2.
begin data
1 12 0
1 23 1
1 22 0
3  5 0
3  7 0
3 13 1
5  1 0
5 56 1
end data.

sort cases by group.
compute id = 1.
if group = lag(group) id = lag(id) + 1.
exe.

list group id v1 v2 .

   group       id       v1       v2 
 
    1.00     1.00    12.00      .00 
    1.00     2.00    23.00     1.00 
    1.00     3.00    22.00      .00 
    3.00     1.00     5.00      .00 
    3.00     2.00     7.00      .00 
    3.00     3.00    13.00     1.00 
    5.00     1.00     1.00      .00 
    5.00     2.00    56.00     1.00 
 
 
Number of cases read:  8    Number of cases listed:  8

How to cite this page

Report an error on this page

UCLA Researchers are invited to our Statistical Consulting Services
We recommend others to our list of Other Resources for Statistical Computing Help
These pages are Copyrighted (c) by UCLA Academic Technology Services


The content of this web site should not be construed as an endorsement of any particular web site, book, or software product by the University of California.