【问题标题】:Function based on lists not working as expected基于列表的功能未按预期工作
【发布时间】:2021-06-10 02:21:21
【问题描述】:

我正在尝试构建这个函数,它需要两个列表和一个输入。

到目前为止我所拥有的:

CLV_general <- function(profit, alpha, r){
  CLV = 0
  t = length(profit)
  for (i in 1:length(profit)){
    for (p in profit){m = p}
    for (t in 0:t){T = t}
    for(a in alpha){A = a}
    clv = (m*A)/((1 +r)^T)
    CLV = CLV + clv
   }
 return(CLV)
}

调用函数是基于关闭的:

alpha = c(1, .96, .92, .88, .84, .80)
profits = c(100, 100, 100, 100, 100,100)
CLV_general(profits, alpha, .10)

但返回值 270.9475 但它应该返回值:

> (100*1/((1+.10)^0)) + (100*.96/((1+.10)^1)) + (100*.92/((1+.10)^2)) + (100*.88/((1+.10)^3)) + (100*.84/((1+.10)^4)) + (100*.80/((1+.10)^5))
[1] 436.4683

该函数基于公式 SUM(Mt*At/((1+r)^t) 其中 Mt 是上述利润中的每个值顺序值,A 是上述 alpha 的顺序值,比率是常数,t是时间 0 到利润或 alpha 的长度。

我已经坚持了 5 个小时,我只是想念一些东西。谢谢!!!

【问题讨论】:

    标签: r function for-loop


    【解决方案1】:

    这似乎是一个矢量化操作。试试看:

    CLV_general <- function(profit, alpha, r){
      sum((profit*alpha/((1 + r)^(seq_along(alpha) - 1))))
    }
    
    alpha = c(1, .96, .92, .88, .84, .80)
    profits = c(100, 100, 100, 100, 100,100)
    CLV_general(profits, alpha, .10)
    #[1] 436.4683
    

    【讨论】:

      猜你喜欢
      • 2013-08-29
      • 2020-04-28
      • 2021-08-27
      • 1970-01-01
      • 2012-10-07
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多