2015-10-14 53 views
-3

a是我的data.frame。 如何通過更新pi_hat,theta_hat,lambda_hat的值來運行Zi_hat函數100次?而每一次顯示pi_hattheta_hat結果,lambda_hat運行100次函數

Zi <- function(x){ 
    x <- zi_hat=(pi_hat*theta_hat*exp(-theta_hat*a))/(pi_hat*theta_hat*exp(-theta_hat*a)+(1-pi_hat)*lambda_hat*exp(-lambda_hat*a)) 


    pi_hat=(1/n)*sum(zi_hat) 
    theta_hat=sum(zi_hat)/(sum(zi_hat*a)) 
    lambda_hat=(n*sum(zi_hat))/(n*sum(a)-sum(zi_hat)*sum(a)) 

    c(pi_hat,theta_hat,lambda_hat) #print out the updated data# 
    if (?>100) break 
} 

爲 「?」 我應該在函數中添加另一個語句來使make?

+0

查看'for'-loops或'while' –

回答

0

你可以試試這個

Zi <- function(x){ 
counter = 1 
while(counter <= 100) 
{ 
    x <- zi_hat=(pi_hat*theta_hat*exp(-theta_hat*a))/(pi_hat*theta_hat*exp(-theta_hat*a)+(1-pi_hat)*lambda_hat*exp(-lambda_hat*a)) 
    pi_hat=(1/n)*sum(zi_hat) 
    theta_hat=sum(zi_hat)/(sum(zi_hat*a)) 
    lambda_hat=(n*sum(zi_hat))/(n*sum(a)-sum(zi_hat)*sum(a)) 
    c(pi_hat,theta_hat,lambda_hat) #print out the updated data# 

    counter = counter + 1 
} 
} 
0

感謝@cccmir。非常好的例子。 它必須分別返回zi,pi_hat,lambda_hat和theta_hat。

Zi <- function(pi_hat,theta_hat,lambda_hat){ 
    counter = 1 
    while(counter <= 10000) 
    { 
    zi_hat<-(pi_hat*theta_hat*exp(-theta_hat*a))/(pi_hat*theta_hat*exp(-theta_hat*a)+(1-pi_hat)*lambda_hat*exp(-lambda_hat*a)) 
    pi_hat=(1/n)*sum(zi_hat) 
    theta_hat=sum(zi_hat)/(sum(zi_hat*a)) 
    lambda_hat=(n*sum(zi_hat))/ 
    (n*sum(a)-sum(zi_hat)*sum(a)) 
    counter = counter + 1 
    } 
    return(lambda_hat) 
}