<>
Several things come to mind. Among them: You have to give explanations for
the elements of your code, so that others know what the lines are there for.
It is best to comment out via " /* */" so the comment can stretch across
several lines.
*************
expand 10
gen no = _n
sort id_psu no
drop no
gen no = _n
*************
is too complicated as you first have Stata record the current sort order via
"_n" , then -sort- on "id_psu" and then -drop- "no" - only to recreate it in
the next step.
The line - scalar N = _N- is rarely needed as "_N" is available anytime you
need it. Sometimes you have to turn it into an expression as `=_N' to get
your hands on it.
It is not a good idea to use the running index of your last -forvalues- loop
as a -local- as well.
Overall, why do you always insist on -matrices- when you can have variables?
Also remember you have to put all of this into a -program- to allow
-simulate- to do its magic... See -help simulate- at the bottom for a useful
example.
HTH
Martin
-----Ursprüngliche Nachricht-----
Von: [email protected]
[mailto:[email protected]] Im Auftrag von Susan Olivia
Gesendet: Donnerstag, 28. Mai 2009 01:29
An: [email protected]
Betreff: st: Simulation in Stata
Dear Stata list,
I would like to run Monte Carlo simulation using
artificially simulated autocorrelated data. In each
experiment, the only variable that changes is the dependent
variable (Y).
Below is my programming attempt in creating the Y and am
wondering whether there is more elegant way to implement my
code in Stata. I am a beginner in programming and would
appreciate any programming tips.
Thanks,
Susan
// In this do file, the independent vars and the locations
remain fixed for all iterations, only the dependent variable
changes //
clear
local nrep 250
*qui set obs 100
*gen id_psu = _n
tempvar sdalpha1 sdalpha2
gen `sdalpha1' = uniform()
gen `sdalpha2' = uniform()
* Expand to generate individual observations - here assuming
that each cluster has 10 households *
expand 10
gen no = _n
sort id_psu no
drop no
gen no = _n
gen xcoord = uniform()*100
gen ycoord = uniform()*100
spatwmat, name(W) xcoord(xcoord) ycoord(ycoord) band(0 100)
eigenval(E) standardize
scalar lambda = 0.5
gen constant = 5
mkmat constant
scalar N = _N
matrix Idtot = I(N)
matrix IlambdaW = Idtot-(lambda*W)
matrix invIlambdaW = inv(IlambdaW)
* Generate the predictor & the variable y
gen x = 5 + `sdalpha1'*invnorm(uniform()) + `sdalpha2'
mkmat x
local i = 1
forv i = 1/`nrep'{
gen u`i' = 0.28*invnorm(uniform())
mkmat u`i'
matrix epsilon`i' = invIlambdaW*u`i'
matrix y`i' = constant + x + epsilon`i'
svmat y`i'
local i = `i' + 1
}
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/