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

st: manual weighted average variable in panel data set

 From hind lazrak To statalist@hsphsun2.harvard.edu Subject st: manual weighted average variable in panel data set Date Thu, 15 Nov 2012 16:33:34 -0800

```Hello Stata-listers

I have a panel data set with the following variables: ID time_resid  conc
The repeated observations vary from 1 to 5 for each individual (ID).
Each observation has a time period (time_resid) during which a
pollutant concentration occurs (conc).
Here is an excerpt of the data

list    id conc resid_time counter in 1/7, sepby(id)

+-------------------------------+
id    conc   resid_~e   counter
------------------------------------
1.    20059   15.96        380         1
2.    20059   21.17        100         2
3.    20059   18.07        480         3
------------------------------------
4.    20060      30        181          1
5.    20060   16.68        292         2
------------------------------------
6.    20061   23.78        269         1
7.    20061   18.07        103         2
+------------------------------------+

I need to create a variable using  time_resid and conc that computes
the time-weighted average concentration for each ID.

The steps that I took were to create variable product (equal to
resid_time * conc) and then I have been trying to come up with a loop
that would do the following:
for each person, and each observation compute the time weighted
average concentration =( sum of product / total resid_time up) until
the time at which the observation occurs.

Here's my code:
***************************************
bysort id: gen counter = _n
bysort id: gen product= resid_time*conc

bysort id: gen time = resid_time if _n==1 | counter[_N]==1
bysort id: gen twa= conc if _n==1 | counter[_N]==1
qui su counter
forval i=1/`r(max)' {
bysort id: replace product= product+ product[_n-`i'] if _n!=1
bysort id: replace time= resid_time+ resid_time[_n-`i'] if _n=1
}
bysort id: gen twa = product/time

**********************************************

Unfortunately, this codes generates missing values except when _n==1.
I would appreciate your advice on how and what to fix in the code.

Thank you.

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