Home > Blockchain >  Calculate Mean and Variance of function output
Calculate Mean and Variance of function output

Time:11-05

I have the following code which outputs 1000 MLEs, how do I calculate the mean and variance of the output and include it into the function? I want the output to be; f2d(5) = mean value and variance value

f2d = function(n){
  fun = function(y){
    optimise(
      function(theta){ sum(dpois(y, theta, log = TRUE)) }, 
      interval = c(0,50), 
      maximum = TRUE
    )
  }
# apply the function to each poisson sample
  x = replicate(1000, rpois(n, 10))
  apply(x, 2, fun)
  }

CodePudding user response:

optimise returns a named list with two elements, maximum and objective. The mean/variance (lambda) for dpois is going to be maximum. Have fun return just maximum:

f2d <- function(n){
  fun = function(y){
    optimise(
      function(theta){ sum(dpois(y, theta, log = TRUE)) }, 
      interval = c(0,50), 
      maximum = TRUE
    )$maximum
  }
  # apply the function to each poisson sample
  x = replicate(1000, rpois(n, 10))
  apply(x, 2, fun)
}

BTW, since the MLE of lambda is the mean of the observations and sums of Poisson random variables are also Poisson-distributed, you could replace f2d with

f2d <- function(n) rpois(1e3, 10*n)/n
  • Related