How to draw observations from a normal distribution and compute the mean using a customized estimator, and then running this procedure in a loop in r

I want to use a custom estimator Yhat=(1/(n-4))*sum(Y_i) as an estimator for the mean of Y_i.

How do I draw, say, 20 observations from the distribution N(4,10) and compute the estimate of the sample mean using Yhat, and then repeat this procedure k amount of times in a loop and save the results in a matrix in r?

1 answer

  • answered 2021-09-22 20:19 wiper8

    First, since you want the estimate of the mean, you don't need a matrix, a vector should be fine.

    Yhat <- function(x) {
      if (length(x) <= 4) {
        stop("vector x must be at least 5 elements long")
      } else {
        sum(x) / (length(x) - 1)
      }
    }  
    
    k <- 100
    
    result <- replicate(k, {
      simulations <- rnorm(20, 4, 10)
      Yhat(simulations)
    })
    
    result
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum