Date: Sun, 18 Jul 2010 22:20:27 -0400
Reply-To: Ian Whitlock <iw1sas@GMAIL.COM>
Sender: "SAS(r) Discussion" <SAS-L@LISTSERV.UGA.EDU>
From: Ian Whitlock <iw1sas@GMAIL.COM>
Subject: Re: Counter
Content-Type: text/plain; charset=ISO-8859-1
Hari,
I would vote for a traditional SAS solution using SAS dates. It is a simple
merge problem, so use a simple merge.
data alldata;
input subject $ date :mmddyy10. flag;
datalines;
Subject1 5/1/2010 0
Subject1 6/1/2010 0
Subject1 7/1/2010 1
Subject1 8/1/2010 0
Subject1 9/1/2010 0
Subject1 10/1/2010 0
Subject2 1/1/2010 0
Subject2 2/1/2010 1
Subject2 3/1/2010 0
Subject2 4/1/2010 0
;
data wanted err;
merge alldata
alldata ( keep = subject date flag
rename = (flag=_flag date=_date)
where = (_flag = 1)
in = wanted
) ;
by subject ;
if wanted then
index = intck ( "month", _date, date ) ;
else
if first.subject then
output err ;
output wanted ;
run ;
One advantage here is that if a month is skipped you will still have
stable indices if data is later added. If no months are skipped then
solutions that depend on counting records and this solution produce
the same result. A second advantage is that the code does some error
checking.
This solution is essentially like Chang's except that he chose SQL.
In this case the traditional merge looks simpler. Defensive coding is
always a wise policy. If you are worried about gaps then use the LAG
or DIF function to compare adjacent indices.
Ian Whitlock
==============
Date: Fri, 16 Jul 2010 21:47:59 -0400
From: SUBSCRIBE SAS-L Anonymous <hari.sas.j@GMAIL.COM>
Subject: Counter
Hi,
I have a dataset with three variables, subject date flag. Basically I need
to index in such a away that as soon as the flag = 1 then index is set 0 and
any observation which has a lower value date is indexed -1, -2 and so on ..
and any observation that has higher date value than the (flag = 1) is
indexed +1, +2 and so on within the group subject.Below is the program that
creates raw data and also the desired output is shown below as well
data alldata;
input subject $ date $12. flag;
datalines;
Subject1 5/1/2010 0
Subject1 6/1/2010 0
Subject1 7/1/2010 1
Subject1 8/1/2010 0
Subject1 9/1/2010 0
Subject1 10/1/2010 0
Subject2 1/1/2010 0
Subject2 2/1/2010 1
Subject2 3/1/2010 0
Subject2 4/1/2010 0
;
run;
data alldata1;
set alldata (rename = (date = datem));
date = input(datem,mmddyy10.);
format date date9.;
run;
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Desired output:
subject date flag index
Subject1 5/1/2010 0 -2
Subject1 6/1/2010 0 -1
Subject1 7/1/2010 1 0
Subject1 8/1/2010 0 1
Subject1 9/1/2010 0 2
Subject1 10/1/2010 0 3
Subject2 1/1/2010 0 -1
Subject2 2/1/2010 1 0
Subject2 3/1/2010 0 1
Subject2 4/1/2010 0 2
Advanced thanks for help
Regards,
Hari