r语言 - 这段代码有什么问题?我必须加2才能找出原始答案?



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

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

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

这告诉我们,当我们向test输入 20k 时,我们得到 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

最新更新