Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: generate with varying number of previous observations


From   Maarten buis <[email protected]>
To   [email protected]
Subject   Re: st: generate with varying number of previous observations
Date   Sat, 26 Jan 2008 16:17:06 +0000 (GMT)

--- William Bishop <[email protected]> wrote:

> I want to generate a variable by making calculations comparing the
> current observation to ALL the previous observations with the same
> id.
> 
> Let's say I want to sum the difference in variable x for the
> observation 5 vs all the previous obs. It would look something like:
> 
> gen diffx=(x[5]-x[4])+(x[5]-x[3])+(x[5]-x[2])+(x[5]-x[1])

Here is a solution without resorting to a loop:

*----------------- begin example -------------------
drop _all
input id obs x 
1 1 2 
1 2 5 
1 3 6 
1 4 8 
1 5 11 
2 1 3 
2 2 4 
2 3 6 
2 4 7 
2 5 9 
2 6 11 
end

sort id obs
by id (obs): gen diffx = _n*x - sum(x)
list
*----------------------- end example ------------------
(For more on how to use examples I sent to the Statalist, see
http://home.fsw.vu.nl/m.buis/stata/exampleFAQ.html )

Hope this helps,
Maarten



-----------------------------------------
Maarten L. Buis
Department of Social Research Methodology
Vrije Universiteit Amsterdam
Boelelaan 1081
1081 HV Amsterdam
The Netherlands

visiting address:
Buitenveldertselaan 3 (Metropolitan), room Z434

+31 20 5986715

http://home.fsw.vu.nl/m.buis/
-----------------------------------------


      __________________________________________________________
Sent from Yahoo! Mail - a smarter inbox http://uk.mail.yahoo.com

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index