For循环返回重复的NA值

时间:2019-06-14 03:48:59

标签: r

我想使用此for循环来确定我放置在MillerBids向量中的每个“出价”所产生的利润。输出必须是包含10个元素的向量。问题在于此代码仅返回重复的NA值。

我认为错误是在索引编制中的某处或重置了变量和向量。当处理更复杂的循环时,这是我很难理解的两件事。

library(triangle)

MillerBids = c(10500,11000,11500,12000,12500,13000,13500,14000,14500,15000)

CostToBid = 350
ProjCost = 10000
Comps = 4

MillerProfs = c()
for (MillerBid in MillerBids) {
  CompBids = c()
  MillerProf = 0
  for (Comp in 1:Comps) 
    CompBids[Comp] = MillerBid * rtriangle(1, a=0.9, b=1.8, c=1.3)
  MinComp = min(CompBids)
  if (MillerBid < MinComp) {
    MillerProf = MillerBid - (CostToBid + ProjCost)
  } else { 
    MillerProf = 0 - CostToBid 
  }
  MillerProfs[MillerBid] = MillerProf
}
MillerProfs

返回:[1] NA NA NA NA NA NA NA NA ...几千次

我知道使用apply()函数系列的好处,但是对于这个特定的实例,我需要使用它的for循环,并且我还需要提高对它们的理解。

正如我所说,目标是使MillerProfs是具有10个元素的向量,每个元素都是与MillerBids中的值有关的利润数字。

1 个答案:

答案 0 :(得分:3)

执行时在代码中

MillerProfs[MillerBid] = MillerProf

在第一次迭代中,MillerBid的值是向量MillerBids中的第一个值10500,因此,计算值(MillerProf)被存储在该索引处,并且所有中间值都被翻转到NA。

这就像在做

x = numeric()
x[5] = 10
x
#[1] NA NA NA NA 10

类似地,在您的情况下,所有前10499个值都是NA,而您的实际值存储在10500索引中。其余的迭代也发生了同样的事情。

相反,请尝试遍历其索引

library(triangle)

MillerProfs <- numeric(length(MillerBids))

for (i in seq_along(MillerBids)) {
   CompBids = 0
   MillerProf = 0
   for (Comp in 1:Comps) 
      CompBids[Comp] = MillerBids[i] * rtriangle(1, a=0.9, b=1.8, c=1.3)
   MinComp = min(CompBids)
   if (MillerBids[i] < MinComp) {
     MillerProf = MillerBids[i] - (CostToBid + ProjCost)
  } else { 
      MillerProf = 0 - CostToBid 
  }
  MillerProfs[i] = MillerProf
}


MillerProfs
# [1]  150  650 1150 1650 2150 2650 3150 3650 4150 4650