这是一个非常简单的版本,应该可以满足您的需求:
forv i = 1/51{
gen s`i' = 0
forv year = 1996/1999{
replace s`i' = s`i' + 0.25 if state_`year' == `i'
}
}
这是一个更通用的版本,应该适用于任意数量的州和年份,以防它对任何人有用:
// Count how many years there are
ds state_????
local yearVars `r(varlist)'
local numYears: list sizeof yearVars
di `numYears'
// What fraction of the total time is one year?
local myFrac = 1/`numYears'
di `myFrac'
// Get a list of all values state_???? can take
foreach var in `yearVars'{
levelsof `var'
local tempYears `r(levels)'
local allStates: list allStates | tempYears
}
// Loop over all states to create the variables you want
foreach i in `allStates'{
gen s`i' = 0
foreach var in `yearVars'{
replace s`i' = s`i' + `myFrac' if `var' == `i'
}
// Make sure you don't get any wacky values here
assert s`i' >=0 & s`i' <= 1
}
// Make sure total time adds up to 1
egen totaltime = rowtotal(s? /* s?? */) // uncomment s?? if you've got between 10 and 99 states; I bet you do
assert totaltime == 1
drop totaltime