# Computing Expected Values
# It is often times difficult to solve for the expected value of a variable in closed form.
# However, using computers it can be easy to approximate.
# Imagine (for whatever reason) you would like to calculate the expected value of exp(x) where x is distributed as a standard normal distribution.
# Method 1: Randomly draw many draws of the variable and take the mean.
draws = 100000
rvar = exp(rnorm(draws))
mean(rvar)
# Method 2: Draw from the inverse CDF
draws = 100000
CDF = seq(0.0000001,.9999999,length.out=draws)
rvar = exp(qnorm(CDF))
mean(rvar)
# Both methods are likely to produce very similar results. Method 2 might be preferred because it is not succeptable to the random draw. However, Method 1 has the strength of not having to specify and upper and lower limit to the CDF.
# Sometimes you might be interested in estimating the expected value of a censored variable.
# Say we are interested in exp(x) where x is still standard normal but missing at 0 and 2 (min = 0 and max = 2).
# This is easy to approximate as well.
draws = 100000
rvar = rnorm(draws)
rvar.cens <- exp(rvar[(rvar >= 0)&(rvar <= 2)])
mean(rvar.cens)