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 |
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;
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;
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;
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!
Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.
Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
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.