在R中的for循环中求和

时间:2017-07-04 16:29:40

标签: r loops for-loop sum

我正在努力研究如何在R中编码这个总和;我猜测我们可以以某种方式使用for循环,但无法理解它。

我想要编写的等式是:

  

n- \ sum_ {k = 0} ^ {n-1}为n =选择(n-1,k) beta_k exp(k L nk) 1,2,...

Math Latex formula

其中:

  1. beta_k是我已经拥有的矢量
  2. L是常数。
  3. 我已经手动对此进行了编码,但希望将其置于某种for循环中。

    mu3<-3-choose(2,1)*beta1*exp(-1*lambdaL*(3-1))-choose(2,2)*beta2*exp(-2*lambdaL*(3-2))
    mu4<-4-choose(3,1)*beta1*exp(-1*lambdaL*(4-1))-choose(3,2)*beta2*exp(-2*lambdaL*(4-2))-choose(3,3)*beta3*exp(-3*lambdaL*(4-3))
    mu5<-5-choose(4,1)*beta1*exp(-1*lambdaL*(5-1))-choose(4,2)*beta2*exp(-2*lambdaL*(5-2))-choose(4,3)*beta3*exp(-3*lambdaL*(5-3))-choose(4,4)*beta4*exp(-4*lambdaL*(5-4))
    

    lambdaL<-0.5
    

    这是我的测试版列表

    betarec(10,0.5)
     [1] 0.0000000 1.0000000 0.7869387 1.0278660 1.5510843 2.3702034 3.4694342 
    4.7718938
     [9] 6.1685468 7.5667952 8.9154479
    

    谢谢!

1 个答案:

答案 0 :(得分:0)

考虑嵌套 apply 调用,mapply迭代地将 n k args传递给嵌入式sapply循环遍历从1到当前 k 的所有连续beta,并迭代求和结果。

<强>输入

lambdaL <- 0.5
beta <- c(0.0000000,1.0000000,0.7869387,1.0278660,1.5510843,2.3702034,
          3.4694342,4.7718938,6.1685468,7.5667952,8.9154479)

当前版本

mu3<-3-choose(2,1)*beta[1]*exp(-1*lambdaL*(3-1))-choose(2,2)*beta[2]*exp(-2*lambdaL*(3-2))
mu3
# [1] 2.632121
mu4<-4-choose(3,1)*beta[1]*exp(-1*lambdaL*(4-1))-choose(3,2)*beta[2]*exp(-2*lambdaL*(4-2))-choose(3,3)*beta[3]*exp(-3*lambdaL*(4-3))
mu4
# [1] 3.418404
mu5<-5-choose(4,1)*beta[1]*exp(-1*lambdaL*(5-1))-choose(4,2)*beta[2]*exp(-2*lambdaL*(5-2))-choose(4,3)*beta[3]*exp(-3*lambdaL*(5-3))-choose(4,4)*beta[4]*exp(-4*lambdaL*(5-4))
mu5
# [1] 4.405454

循环版 (相当于以前版本的输出)

mu_formula <- function(n,k) {
   n + sum(sapply(seq(k), function(i)
           -choose((n-1),i)*beta[i]*exp(-i*lambdaL*(n-i))))
}

mu_vector <- setNames(mapply(mu_formula, 3:5, 2:4), paste0("mu", 3:5))
mu_vector
#      mu3      mu4      mu5 
# 2.632121 3.418404 4.405454 

mu_list <- setNames(Map(mu_formula, 3:5, 2:4),paste0("mu", 3:5))    
mu_list
# $mu3
# [1] 2.632121

# $mu4
# [1] 3.418404

# $mu5
# [1] 4.405454

广义循环 (适用于所有测试版)

mu_list <- setNames(Map(mu_formula,seq_along(beta)[-1]+1,seq_along(beta)[-1]),
                    paste0("mu",seq_along(beta)[-1]+1))
mu_list

# $mu3
# [1] 2.632121

# $mu4
# [1] 3.418404

# $mu5
# [1] 4.405454

# $mu6
# [1] 5.507972

# $mu7
# [1] 6.640989

# $mu8
# [1] 7.756735

# $mu9
# [1] 8.840919

# $mu10
# [1] 9.896983

# $mu11
# [1] 10.93315

# $mu12
# [1] 11.95646