在R中的while循环中迭代的问题

时间:2019-06-25 12:33:09

标签: while-loop

为什么while循环迭代不起作用? 我需要进行迭代的功能,但无法正常工作。 显然正确的内部计算,但是当我尝试使用while循环迭代它们时,它只会执行一次计算,而不会 迭代地假设是 我希望你能帮助我

代码

iter = 0   暴击= 1

while (crit >= tol && iter < maxit) {

iter = iter+1
mu1= matrix(old[1:n], ncol = n)
mu2 = matrix(old[(n+1):(n*2)], ncol = n)
s1 = matrix(old[(n*2+1):(n*2+n*n)], ncol = n)
s2 = matrix(old[(n*6+1):(n*6+n*n)], ncol = n)
df = old[length(old)-2]
lambda = old[length(old)-1]

mixt = lambda*mvtnorm::dmvt(x = x, delta = mu1, sigma = s1, df = 2)+(1-lambda)*mvtnorm::dmvt(x = x, delta = mu2, sigma = s2, df = 2)
H1 = lambda*mvtnorm::dmvt(x = x, delta = mu1, sigma = s1, df = 2) / mixt
H2 = 1- H1
N1 = sum(H1)
N2 = sum(H2)

new$mu[1] = list(apply(X = x, MARGIN = 2, FUN = function(x) {sum(H1*x) / N1}))
new$mu[2] = list(apply(X = x, MARGIN = 2, FUN = function(x) {sum(H2*x) / N2}))
#new$sigma = (lapply(1:k, FUN = function(i){(t(H1*(x-unlist(new$mu[i]))))%*%(t(t(x-unlist(new$mu[i]))))/ N1}))
new$sigma[1] = list((t(H1*(x-unlist(new$mu[1]))))%*%(t(t(x-unlist(new$mu[1]))))/ N1)
new$sigma[2] = list((t(H2*(x-unlist(new$mu[2]))))%*%(t(t(x-unlist(new$mu[2]))))/ N2)
new$k = init$k
new$df = init$df
new$lambda[1] = mean(H1) #In McLachlan is pi 
new$lambda[2] = 1 - new$lambda[1]

solvec = new
crit = abs(unlist(new)-unlist(old))

if (any(is.nan(unlist(solvec)))) break
old=new 

}

0 个答案:

没有答案