I have a dataset named "X' with many observations. This is just a sample dataset. I need atleast two observations for each unique ID. For example my dataset looks like below:
ID date volume
03 jun1996 100
04 jul1996 110
04 jul1996 120
04 aug1996 130
05 jun1996 105
06 jul1996 110
06 jul1996 110
07 Jun1996 120
08 Jun1998 130
My output should look like below:
04 jul1996 110
04 jul1996 120
04 aug1996 130
06 jul1996 110
06 jul1996 110
How do I code in SAS in order to get an output with atleast two observations per ID.
Please guide me
You can use the NOUNIKEY option in PROC SORT as well.
proc sort data=have nounikey out=want;
by id;
run;
proc print data=want;
run;
Use SQL:
data have;
input ID date $ volume;
datalines;
03 jun1996 100
04 jul1996 110
04 jul1996 120
04 aug1996 130
05 jun1996 105
06 jul1996 110
06 jul1996 110
07 Jun1996 120
08 Jun1998 130
;
proc sql;
create table want as
select *
from have
group by ID
having count(*) > 1;
select * from want;
quit;
You can use the NOUNIKEY option in PROC SORT as well.
proc sort data=have nounikey out=want;
by id;
run;
proc print data=want;
run;
Or use a data step (assuming that dataset HAVE is sorted by ID):
data want;
set have;
by id;
if ~(first.id & last.id);
run;
Advantage (over PROC SQL without ORDER BY clause): The order of observations within the BY groups is preserved.
Disadvantage (shared with the PROC SORT approach): If you change your specifications from "at least two" to, say, "at least three observations per ID," there is more to change in the code than just ">1" into ">2".
Or DOW:
data have;
input ID date $ volume;
datalines;
03 jun1996 100
04 jul1996 110
04 jul1996 120
04 aug1996 130
05 jun1996 105
06 jul1996 110
06 jul1996 110
07 Jun1996 120
08 Jun1998 130
;
run;
data want;
_n_=0;
do until(last.id);
set have;
by id;
_n_+1;
end;
do until(last.id);
set have;
by id;
if _n_ gt 1 then output;
end;
run;
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.