首页 > 解决方案 > 如何使用 R 组织 MLE 的输出

问题描述

我为 MLE 估计写下了这个函数,然后将它应用于不同的参数设置。最后,我将所有结果绑定为一个输出。但是不工作我的输出有问题,而且我需要使用 R 程序像附加的图像一样组织输出。 请在此处输入图片描述 有人可以帮助我吗?我应该修复什么以及如何打印所附图片的结果。

先感谢您

rbssn<- function(n,alpha,beta)
{
  if(!is.numeric(n)||!is.numeric(alpha)||!is.numeric(beta))
  {stop("non-numeric argument to mathematical function")}
  if(alpha<=0){ stop("alpha must be positive")}
  if(beta<=0) { stop("beta must be positive") }
  z      <- rnorm(n,0,1)
  r      <- beta*((alpha*z*0.5)+sqrt((alpha*z*0.5)^2+1))^2
  return(r)
}

#Function
mymle <- function(n,alpha,beta,rep)
{
  theta=c(alpha,beta) # store starting values
  #Tables
  LHE=array(0, c(2,rep));
  rownames(LHE)= c("MLE_alpha", "MLE_beta")
  #Bias
  bias= array(0, c(2,rep));
  rownames(bias)= c("bias_alpha", "bias_beta")
  #Simulation
  set.seed(1)
  #Loop
  for(i in 1:rep){
    myx <- exp(-rbssn(n, alpha, beta))
    Score <- function(x) {
      y <- numeric(2)
      y[1] <- (-n/x[1])*(1+2/(x[1]^2)) - (1/(x[2]*x[1]^3))*sum(log(myx)) - (x[2]/(x[1]^3))*sum(1/log(myx))
      y[2] <- -(n/(2*x[2])) + sum((1/(x[2]-log(myx)))) - (1/(2*(x[1]^2)*(x[2]^2)))*sum(log(myx)) + (1/(2*x[1]^2))*sum(1/(log(myx)))
      y
    }
    Sin <- c(alpha,beta)
    mle<- nleqslv(Sin, Score, control=list(btol=.01))[1]
    LHE[i,]= mle
    bias[i,]= c(mle[1]-theta[1], mle[2]-theta[2])
  }
  
  # end for i
  #Format results
  L <-round(apply(LHE, 1, mean), 3) # MLE  of all the applied iterations  
  bs <-round(apply(bias,1, mean),3) # bias of all the applied iterations 
  row<- c(L, bs)
  #Format a label
  lab <- paste0('n= ',n,';',' alpha= ',alpha,';',' beta= ',beta)
  row2 <- c(lab,row)
  row2 <- as.data.frame(t(row2))
  return(row2)
}

#Bind all
#Example 1
ex1 <- mymle(n = 20,alpha = 1,beta = 0.5,rep = 100)
ex2 <- mymle(n = 50,alpha = 2,beta = 0.5,rep = 100)
ex3 <- mymle(n = 100,alpha = 3,beta = 0.5,rep = 100)
#Example 2
ex4 <- mymle(n = 20,alpha = 0.5,beta = 0.5,rep = 100)
ex5 <- mymle(n = 50,alpha = 0.5,beta = 1,rep = 100)
ex6 <- mymle(n = 100,alpha = 0.5,beta = 1,rep = 100)
df <- rbind(ex1,ex2,ex3,ex4,ex5,ex6)


任何帮助将不胜感激。

标签: rmle

解决方案


推荐阅读