SAS Data Integration Studio, DataFlux Data Management Studio, SAS/ACCESS, SAS Data Loader for Hadoop and others

Assign ID to pairs of consecutive rows

Accepted Solution Solved
Reply
New Contributor
Posts: 2
Accepted Solution

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 IDpairID
1 11
2 21
3 32
4 42
5 53
6 63
7 74
8 84
9 95
10 105
11 115

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

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;

View solution in original post


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

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;

Respected Advisor
Posts: 3,124

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.

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

Discussion stats
  • 3 replies
  • 288 views
  • 2 likes
  • 3 in conversation