【问题标题】:Running a function 100 times运行一个函数 100 次
【发布时间】:2015-10-14 05:53:47
【问题描述】:

a 是我的data.frame。 如何通过更新pi_hattheta_hatlambda_hat 的值来运行Zi_hat 函数100 次?并且每次都显示pi_hattheta_hatlambda_hat的结果

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
}

对于“?” 我应该在函数中添加另一个语句来制作吗?

【问题讨论】:

  • 看看for-loops 或while

标签: r function loops


【解决方案1】:

你可以试试这个

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
 }
}

【讨论】:

    【解决方案2】:

    感谢@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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 2021-10-06
      相关资源
      最近更新 更多