最大似然估计,此处有500 sets of data, size n=100,用了如下的代码。
library(stats4)
muhat <- NULL
sigmahat <- NULL
mu <- 2
sigma <- 2
k <- 500
n <- 100
# Calculate alpha and beta for k times (do k times simulation, each with n data points)
for (j in 1:k) {
y <- rnorm(n, mu, sigma) # True value and sample size
# MOM estimates
mu.mom <- mean(y)
sigma.mom <- (var(y))^0.5
# Negative loglikelihood function (to be minimised)
nloglike <- function(mu, sigma) {
llikei <- suppressWarnings(dnorm(y, mu, sigma))
-sum(log(llikei))
}
# Output
normal.mle <- mle(nloglike, start = list(mu = mu.mom,
sigma = sigma.mom))
muhat[j] <- coef(normal.mle)[[1]]
sigmahat[j] <- coef(normal.mle)[[2]]
}
如果需要用不同的样本量和数据个数做多次模拟,比如样本量为n <- c(20, 30, ... , 100),数据个数k <- c(100, 200, 500),该怎么修改?谢谢