创建临时数组以在r中保持计算

时间:2018-06-05 16:21:19

标签: r

我希望将值0.01附加到临时数组,直到年龄达到30,以便在公式计算中使用每个概率in the Dataframe called Data。例如,对于数据框Age = 21中的第一行,我想根据年龄和概率为每个条目创建一个看起来像这样的临时数组。

x = c(.21,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01)
Data2 = data.frame(x)

然后我在下面的公式中使用它:

for (i in 1:length(Data$Prob))
{
    for (j in 1:length(Data2$x)) {
         Data$NPV[i] = sum(x[j]*CostofFailure[i]*0.025)/(1+0.07)^j)
}
}


  **Dataframe: Data**
  Age  Prob    Cost      NPV 
  21     45       4000     
  24     21       2000

1 个答案:

答案 0 :(得分:0)

如果您需要通过将特定值n次附加到另一个选定值(例如.21)来创建矢量,请尝试使用rep函数。

x = c(.21,rep(0.01,30-21))

将产生结果,

[1] 0.21 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01