Home > Enterprise >  Generate samples of size n and apply function in R?
Generate samples of size n and apply function in R?

Time:11-05

I have the following code to generate my samples of size n, then want to perform an optimise function on the samples. I should get 1000 results from the optimise function but only get 1? Is there a way to perform the optimise function across the rows of 'x'

f2d <- function(n){
  x <- replicate(1000, rpois(n, 10))
  optimise(
    f = function(theta){ sum(dpois(x, theta, log = TRUE)) }, 
    interval = c(0,50), 
    maximum = TRUE
  )
}

CodePudding user response:

The function must be applied to each sample, so define an auxiliary function, fun, to be applied to each column. Then, call the function in an apply loop.

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)
}

set.seed(2021)
res <- f2d(10)
res <- do.call(rbind, res)

head(res)
#     maximum  objective
#[1,] 9.499999 -26.3231 
#[2,] 11.8     -25.62272
#[3,] 9.799998 -31.49774
#[4,] 10.4     -25.40647
#[5,] 10.4     -31.57375
#[6,] 9.899997 -27.67275
  • Related