Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down at the end of May, and its replacement, statalist.org is already up and running.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Counting using a rolling time window


From   Nick Cox <njcoxstata@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: Counting using a rolling time window
Date   Tue, 10 May 2011 14:48:49 +0100

I imagine your example is to be taken with the correction that the
first 1997m8 should be 1997m7. I suggest

bysort id (time) : gen count = sum(action) - sum(action[_n-3])

See also comments in
<http://www.hsph.harvard.edu/cgi-bin/lwgate/STATALIST/archives/statalist.1105/date/article-397.html>
on the expression "a code", which I warn against.

Nick

On Tue, May 10, 2011 at 2:12 PM, Louis, Philippe
<Philippe.Louis@econ.kuleuven.be>

> I have the following problem. My dataset contains an id-number, a time variable measured in months, and a binary variable indicating action or no action. The time frame is not the same for each person (i.e. id 1 is monitored between January 2000 and May 2000, id 2 between August 1997 and October 1997, etc.). The action variable records whether an action happened during that month or not.
>
> I would like to create a new variable that counts the number of positive actions (i.e. action variable equal to 1). More specifically, I am looking for a code that would loop through the dataset and that would count the number of action==1 using a three months' time window (i.e. current month + 2 previous months), resetting the counter at every new id. If less than three months are available, the loop should just count the number of action==1 of the available months.
>
> An example:
> Id      time            action  count
> 1       2000m1  1       1
> 1       2000m2  1       2
> 1       2000m3  1       3
> 1       2000m4  0       2
> 1       2000m5  0       1
> 2       1997m8  0       0
> 2       1997m8  1       1
> 2       1997m9  0       1
> 2       1997m10 1       2
>
> I have been struggling for a while to write a code that would generate the count variable.
>
> Any help or suggestions would be appreciated.

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index