Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


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

Re: st: RE: Looping within a subset under a certain condition


From   "Gerard Solbrig" <[email protected]>
To   <[email protected]>
Subject   Re: st: RE: Looping within a subset under a certain condition
Date   Sat, 29 Sep 2012 21:30:58 +0200

Thanks for the reply and the link. Still, I've ended up with a monstrous
code which doesn't seem to work as it sets rep_ins to . for every
observation.

Just to be clear: for every firm_id, I want to set rep_ins = 1 for every
observation, if its 'trandate' lies within the range ('wind_start' and
'wind_end') of a rep=1 observation of that firm.

gen rep_ins = .
gsort +firm_id -rep +date
by firm_id: gen obs = _n
gen group_obs = _n
qui bysort firm_id: gen obs_N = _N
qui bysort firm_id (group_obs): replace group_obs = group_obs[1]
by group_obs, sort: gen group = _n == 1
replace group = sum(group)
summarize group, meanonly
local max = r(max)
gsort +firm_id -rep +date

forvalues x = 1/`max' {
	local N = obs_N[`x']
	forvalues i = 1/`N' {
		if rep[`i'] == 1 {
		local r = `i'					// to
lock-in the rep = 1 observation
		local s = `i'+1
		forvalues z = `s'/`N' {
			if trandate[`z'] >= wind_start[`r'] & trandate[`z']
<= wind_end[`r'] {
			replace rep_ins = 1 in [`z']
			}
			else {
			replace rep_ins = 0 in [`z']
			}
		}
	}
}
}
replace rep_ins = . if rep == 1
drop obs group group_obs waste obs_N


The first -forval- loop is supposed to count through all the groups of
firm_id's.
The second, embedded -forval- loop should count from observation 1 to _N
WITHIN that group.
The third -forval- loop is supposed to go through all other observations of
that group if it encounters a rep = 1 observation, starting from observation
`i'+1 to _N.

I am not sure how to let Stata count from 1 to _N and `s' to _N,
respectively, within each group of 'firm_id's...

I guess my approach is not totally wrong, and the problem right now is the
syntax. However, there might even be an easier way to solve this problem,
looking at this enormous code.

Thanks in advance! 


*
*   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/


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index