st: Mata Question

 From Danielle H Ferry To StataList Subject st: Mata Question Date Wed, 15 Nov 2006 12:35:55 -0500

Dear Statlisters,
I'm hoping someone can help me with this. I know how to do it in Stata, but not Mata.

Suppose in my pure time series dataset I have a variable, Y, and want to create a new variable, Z, where Z = . if t=1, Z = Y if t = 2, and Z = Z[_n-1] if t>2. After I create a data view, this is simple to implement in Mata (assuming my data is already sorted):

drop _all
set obs 5
ge Y = 1
ge t = _n
scalar N1 = 2

mata
st_view(y=., ., "Y", .)
n1 = st_numscalar("N1")
z = J(rows(y), 1, .)
z[n1,1] = y[n1,1]
for(j=3; j<=rows(z); j++) {
i = j - 1
z[j, .] = z[i, .] + 1
}
end
list

Suppose, now, that I have a panel. I want the same definition for Z to apply WITHIN EACH PANEL. It is clearly this part that needs to be amended somehow, but I'm not sure how to do it best:

z[n1,1] = y[n1,1]
for(j=3; j<=rows(z); j++) {
i = j - 1
z[j, .] = z[i, .] + 1
}

The brute force way would be:

drop _all
set obs 10
ge p = 1 in 1/5
replace p = 2 in 6/l
ge Y = 1
bys p: ge t = _n
scalar N1 = 2
scalar numpanels = 2
scalar numonpanel = 5

mata
st_view(y=., ., "Y", .)
n1 = st_numscalar("N1")
nump = st_numscalar("numpanels")
numonp = st_numscalar("numonpanel")
z = J(rows(y), 1, .)
z[n1,1] = y[n1,1]
for(j=3; j<=rows(z)/nump; j++) {
i = j - 1
z[j, .] = z[i, .] + 1
}
z[n1+numonp,1] = y[n1+numonp,1]
for(j=3+numonp; j<=rows(z); j++) {
i = j - 1
z[j, .] = z[i, .] + 1
}
st_store(., idx, z)
end
list

But this requires me to know a lot about the data a priori. Is there a clever way to do this? In real life I have several different data samples and N1, numpanels, & numonpanels will vary across samples.

Many thanks,
Danielle

```begin:vcard
fn:Danielle H Ferry
n:Ferry;Danielle H
org:Bear Stearns & Co.;Asset Management
email;internet:dferry@bear.com
tel;work:212/272-3415
version:2.1
end:vcard

```
```***********************************************************************
Bear Stearns is not responsible for any recommendation, solicitation,
offer or agreement or any information about any transaction, customer
account or account activity contained in this communication.

Bear Stearns does not provide tax, legal or accounting advice.  You
engaging in any transaction. In order for Bear Stearns to comply with
Internal Revenue Service Circular 230 (if applicable), you are notified
that any discussion of U.S. federal tax issues contained or referred to
herein is not intended or written to be used, and cannot be used, for
the purpose of:  (A) avoiding penalties that may be imposed under the
Internal Revenue Code; nor (B) promoting, marketing or recommending to
another party any transaction or matter addressed herein.
***********************************************************************```