这段代码有什么问题?我必须加 2 才能找出原来的答案?

What's wrong with this code? I have to add 2 to find out the original answer?

我想使用 R 找出 投资回收期。所以我遵循 python 代码并尝试将其转交给 R。但是,我得到的答案总是比正确答案少 2。

我试过加 2,这只是一个简单的 hack。但是,主要问题仍然存在。

cashInflows     <-  data.frame( 
    Year        =   c(1, 2, 3, 4, 5), 
    ProjectA    =   c(10000, 20000, 30000, 40000, 20000), 
    ProjectB    =   c(40000, 30000, 20000, 10000, 20000)
    ) 
total       =   0
years       =   0
cumulative  <-  c()

for (f in cashInflows$ProjectB){
    total       =   f + total
    if (total   < cashOutflows){
        years = years + 1
    cumulative <-   append(cumulative, total)
   }
}

A  <- years - 1
B  <- cashOutflows - cumulative[years]
C  <- cashInflows$ProjectB[years + 2] # Why +2 ???????? ( I don't know specifically yet.)
print (A + (B/C))

这是经过一些修改后的一些工作代码。

1) 正如其他人指出的那样,您需要在某处定义 cashOutflows 以便 运行。

2) R 使用基于 1 的索引,因此如果您有访问向量的第 0 个索引的代码,您将无法获得预期的结果。我已将 years 更改为从 1 开始,这样如果递增循环从未被调用(即我们在第 1 年内通过盈亏平衡),我们将得到一个有效数字 (0) 而不是 NULL。

我已将代码放入名为 test 的函数中,该函数将 cashOutflows 作为输入。

total       =   0
years       =   1
cumulative  <-  0

test <- function(cashOutflows) {
  for (f in cashInflows$ProjectB){
    total       =   f + total
    if (total   < cashOutflows){
      years = years + 1
      cumulative <-   append(cumulative, total)
    }
  }

  A  <- years - 1
  B  <- cashOutflows - cumulative[years]
  C  <- cashInflows$ProjectB[years] 
  return (A + (B/C))
}

然后我们可以用一些输入来尝试这个函数,这会产生我预期的输出:

> as.numeric(lapply(c(20000, 39999, 40000, 40001, 70000, 80000), test))
[1] 0.500000 0.999975 1.000000 1.000033 2.000000 2.500000

这告诉我们,当我们将 20k 投入 test 时,我们得到 0.5,因为这是第一年 40k 流入量的一半。当我们将 39.999k 输入函数时,我们得到 0.9999 年的盈亏平衡时间,因为我们不需要一整年的 40k 来实现盈亏平衡。


可以说,像下面这样的方法对于 R 来说会更惯用,我们使用像 cumsum 这样的内置向量化函数。

cashOutflows <- 70000
output <- cashInflows
output$cuml = cumsum(output$ProjectB)       # Add column with cumulative total
output$excess = output$cuml - cashOutflows  # Calc "excess" over breakeven
output <- subset(output, excess >= 0)[1, ]  # Select first year at or beyond breakeven
output$Breakeven = output$Year - output$excess/output$ProjectB
output$Breakeven