【问题标题】:Generate samples of size n and apply function in R?生成大小为 n 的样本并在 R 中应用函数?
【发布时间】:2021-12-18 07:07:09
【问题描述】:

我有以下代码来生成大小为 n 的样本,然后想对样本执行优化功能。我应该从优化函数中得到 1000 个结果,但只能得到 1 个?有没有办法在'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
  )
}

【问题讨论】:

    标签: r function optimization random statistics


    【解决方案1】:

    函数必须应用于每个样本,因此定义一个辅助函数fun,以应用于每一列。然后,在apply 循环中调用该函数。

    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
    

    【讨论】:

    • 感谢您的澄清!如果我想取 1000 个输出的均值和方差,如何将其实现到函数中?
    • @Monj 不要使函数复杂化,因为有colMeans(res) 的意思,而对于方差apply(res, 2, var)