10.11 Useful Examples - Optimizing

Useful when…

  • Want to pass function on to optimise()/optimize()
  • Want to perform pre-computations to speed things up
  • Want to re-use this for other datasets

(Skipping to final results from section)

Here, using MLE want to to find the most likely value of lambda for a Poisson distribution and this data.

x1 <- c(41, 30, 31, 38, 29, 24, 30, 29, 31, 38)

We’ll create a function that creates a lambda assessment function for a given data set.

ll_poisson <- function(x) {
  n <- length(x)
  sum_x <- sum(x)
  c <- sum(lfactorial(x))

  function(lambda) {
    log(lambda) * sum_x - n * lambda - c
  }
}

We can use this on different data sets, but here use ours x1

ll <- ll_poisson(x1)
ll(10)  # Log-probility of a lambda = 10
#> [1] -183.6405

Use optimise() rather than trial and error

optimise(ll, c(0, 100), maximum = TRUE)
#> $maximum
#> [1] 32.09999
#> 
#> $objective
#> [1] -30.26755

Result: Highest log-probability is -30.3, best lambda is 32.1