## Monday, March 25, 2013

### asim command

* After using the msim command from a previous post, I decided I did not like having many different variables for each simulation run.

* So I have recoded an alternative command called asim

* This command allow subsequent simulate commands to be run, saving the old data in memory appended to the current data.
cap program drop asim
program define asim
* This will allow the user to specify a value to assign to the asim variable which is generated after the simulation is run.
gettoken before after : 0 , parse(":")
local simulation = subinstr("after'", ":", "", 1)

tempfile tempsave
cap save tempsave'
simulation'

* This will append in the new simulation data to the old data set.
gen asim = "before'"
cap append using tempsave'
end

* Let's write a nice little program that we would like to simulate.
cap program drop simCLT
program define simCLT

clear
set obs 1'
* 1 is defined as the first argument of the program sim

* Let's say we would like to see how many observations we need for the central limit theorem (CLT) to hold for a bernoulli distribution.
gen x = rbinomial(1,.25)

sum x
end

* So let's see first how the simulate command works initially.

simulate, rep(200): simCLT 100

* The simulate command will automatically save the returns from the sum command as variables (at least in version 12)

* But instead let's try our new command!
clear
* Clear out the old results
asim 0100: simulate, rep(200): simCLT 100

asim 0200: simulate, rep(200): simCLT 200

* Looks good!

asim 0400: simulate, rep(200): simCLT 400

asim 1000: simulate, rep(200): simCLT 1000

asim 10000: simulate, rep(200): simCLT 1000

asim 100000: simulate, rep(200): simCLT 1000

* Standardize the individual means of each run so as to more easily compare them with each other.
bysort asim: egen sd_mean = sd(mean)
bysort asim: egen mean_mean = mean(mean)

gen std_mean = (mean-mean_mean)/sd_mean

hist std_mean, kden by(asim)
* We can see that this generate data is much easier to use than that using many different variables.

* It looks a little funny with some of the numbers having zeros in front.  However, this was the best way to do it given that the asim variable is text.