BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
STLT
Calcite | Level 5

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
1 ACCEPTED SOLUTION

Accepted Solutions
Reeza
Super User

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

3 REPLIES 3
Reeza
Super User

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;

Haikuo
Onyx | Level 15

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;
STLT
Calcite | Level 5

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!

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

Register now!

How to connect to databases in SAS Viya

Need to connect to databases in SAS Viya? SAS’ David Ghan shows you two methods – via SAS/ACCESS LIBNAME and SAS Data Connector SASLIBS – in this video.

Find more tutorials on the SAS Users YouTube channel.

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