Help using Base SAS procedures

Delete consecutive observations if same

Reply
Occasional Contributor
Posts: 16

Delete consecutive observations if same

My data set has the following form:

subject treatment dateprescribed
1 A 08/08/1997
1 A 09/12/1998
1 A 12/01/1999
1 B 07/09/2000
1 B 05/09/2001
1 A 05/06/2002
1 A 06/10/2002
1 A 09/11/2003
2 A 08/03/1996
2 A 09/12/1998
2 B 12/01/1999
2 B 07/09/2000
2 B 05/09/2001
2 A 05/06/2002
2 A 06/10/2002
2 B 09/11/2003

I want to delete the row if the treatment in that row is the same as the
previous treatment; Thus I want to obtain the following:
subject treatment dateprescribed
1 A 08/08/1997
1 B 07/09/2000
1 A 05/06/2002
2 A 08/03/1996
2 B 12/01/1999
2 A 05/06/2002
2 B 09/11/2003

Thus patient 1 received the treaments in the order ABA, while patient 2 received the treatments in the order ABAB . Can someone help me on how to do that in SAS.

Best wishes
Super Contributor
Posts: 359

Re: Delete consecutive observations if same

Sort by subject treatment dateprescribed.

data xxx;
by subject treatment dateprescribed;
if first.treatmant;
run;
Respected Advisor
Posts: 3,777

Re: Delete consecutive observations if same

> Sort by subject treatment dateprescribed.
>
> data xxx;
> by subject treatment dateprescribed;
> if first.treatmant;
> run;

This wont work because the data need to be ordered by date, not treatment. But, the FIRSTing needs to be done by TREATMENT. The NOTSORTED by statement option is the key.


[pre]
data rx;
input (subject treatment dateprescribed)(2*:$1. :mmddyy.);
format date: mmddyy10.;
cards;
1 A 06/10/2002 I mixed up the lines a bit
1 A 09/11/2003
1 A 08/08/1997
1 B 07/09/2000
1 B 05/09/2001
1 A 05/06/2002
1 A 09/12/1998
1 A 12/01/1999
2 A 08/03/1996
2 A 09/12/1998
2 B 12/01/1999
2 B 07/09/2000
2 B 05/09/2001
2 A 05/06/2002
2 A 06/10/2002
2 B 09/11/2003
;;;;
run;
proc sort;
by s: d:;
run;
proc print;
by s: t: notsorted;
id s: t:;
var d:;
run;

data firstInSequence;
set;
by s: t: notsorted;
if first.treatment;
run;
proc print;
by s:;
id s:;
run;
[/pre]
Contributor
Posts: 24

Re: Delete consecutive observations if same

May also;

data result;
set old;
if subject = lag(subject) and treatment = lag(treatment) then delete;
run;
Super User
Posts: 10,550

Re: Delete consecutive observations if same

Or this may work:

Proc Sort data=old out=new noduprecs; by x y z;run;
Ask a Question
Discussion stats
  • 4 replies
  • 166 views
  • 0 likes
  • 5 in conversation