Solved
New Contributor
Posts: 2

# Assign ID to pairs of consecutive rows

Hi,

I have a dataset of individuals already sorted on a value. I would like to assign a pairID to the first two individuals, then the next pair, and so on. If the file contains an odd number of individuals, the last three are grouped to form a triplet. I hope that makes sense and would appreciate any tips.

Thanks!

 HAVE WANT ID ID pairID 1 1 1 2 2 1 3 3 2 4 4 2 5 5 3 6 6 3 7 7 4 8 8 4 9 9 5 10 10 5 11 11 5

Accepted Solutions
Solution
‎01-30-2017 12:15 PM
Super User
Posts: 23,237

## Re: Assign ID to pairs of consecutive rows

Playing around with some basic math this is relatively straightforward.

Functions:

MOD()

Use NOBS option on SET statement to get the number of observations.

Use RETAIN

Data want;

set have NOBS=num end =eof;

RETAIN count;

If mod(_n_, 2) ne 0 and not eof then count+1;

run;

All Replies
Solution
‎01-30-2017 12:15 PM
Super User
Posts: 23,237

## Re: Assign ID to pairs of consecutive rows

Playing around with some basic math this is relatively straightforward.

Functions:

MOD()

Use NOBS option on SET statement to get the number of observations.

Use RETAIN

Data want;

set have NOBS=num end =eof;

RETAIN count;

If mod(_n_, 2) ne 0 and not eof then count+1;

run;

Posts: 3,167

## Re: Assign ID to pairs of consecutive rows

Of course I would choose to use @Reeza's solution myself, but FWIW, here is another approach outrageously not using MOD() ,

``````data want;
do _error_=1 to 2;
set sashelp.class end=last;
pairID=ifn(last and _error_=1,_n_-1,_n_);
output;
end;
run;``````
New Contributor
Posts: 2

## Re: Assign ID to pairs of consecutive rows

Thank you, both, for taking time to resolve this for me. I can't believe how few lines of codes are needed. I understand the logic, but am just not advanced enough to come up with it myself. Thanks again for the help!

☑ This topic is solved.