我有一个适度的函数来为人口估计生成MLE的迭代。 (我知道R中的迭代形式很差,但我试图详细显示非线性搜索过程,以及Excel电子表格中的方法)。
n <- c(32,54,37,60,41) # number of captures
R <- c(32,36,6,13,5) # of marked fish returned to the population
fn <- function(x){
N = 97 #starting value of N
mle = matrix(0, nrow=x, ncol=8) #per suggestion
colnames(mle) = c("N","g.N","h.N","N1","g.N1","h.N1","delta.h","corr") #added column names
for (i in 1:x) {
g.N = prod(1-n/N)
h.N = N-sum(R)-N*g.N
N1 = N-1
g.N1 = prod(1-n/N1)
h.N1 = N1-sum(R)-N*g.N1
delta.h = h.N-h.N1
corr = -h.N/delta.h
#print(c(N,g.N,h.N,N1,g.N1,h.N1,delta.h,corr))#original output
mle[i,] = c(N,g.N,h.N,N1,g.N1,h.N1,delta.h,corr) #per suggestion
N = N+corr
}
return(mle) #per suggestion
}
fn(5)
这会创建以下输出
N g.N h.N N1 g.N1 h.N1 delta.h corr
[1,] 97.00000 0.04046356 1.075034e+00 96.00000 0.03851149 0.2643856 0.8106486 -1.326141e+00
[2,] 95.67386 0.03788200 4.954192e-02 94.67386 0.03597455 -0.7679654 0.8175073 -6.060119e-02
[3,] 95.61326 0.03776543 2.382189e-03 94.61326 0.03586008 -0.8154412 0.8178234 -2.912841e-03
[4,] 95.61035 0.03775983 1.147664e-04 94.61035 0.03585458 -0.8177238 0.8178386 -1.403289e-04
[5,] 95.61020 0.03775956 5.529592e-06 94.61020 0.03585432 -0.8178338 0.8178393 -6.761220e-06
我想清理输出,但是无法破解代码将结果放入矩阵或data.frame或任何我可以给出列标题并调整数字,数字格式等的格式。以有意义的方式。我在猫和格式方面取得了有限的成功,但却无法让他们按照我的意愿去做。任何帮助将其格式化为表格,矩阵或data.frame都将不胜感激。
答案 0 :(得分:1)
您的功能实际上对我不起作用(例如n
)。无论如何,你应该有类似的东西:
N<-97 #starting value of N
m = matrix(0, nrow=5, ncol=7)
for (i in 1:x) {
#<snip>
m[i,] = c(N,g.N,N1,g.N1,h.N1,delta.h,corr)
N<-N+corr
}
return(m)
}