我在 r 中有以下数字向量
bay_no <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
bay_cont <- c(45,25,25,0,19,61,2,134,5,27,0,54,102,97,5,6,65,47,85,0)
count <- 3
bay_to_serve <- sum(bay_cont)/count
在上面的bay_cont
向量中,我想找到接近bay_to_serve
上述情况的总和bay_to_serve = 268
现在,从(45 till 2) sum is 177 and (45 till 134) sum is 311
,311 is closest to 268
那么它应该返回的索引i.e 8 from bay_no
我们将从中得到一个向量 bay_no = 1-8
再次从 bay_cont from 5 till the sum close to 268
期望的输出是
bay_no 1-8,9-14 and then remaining bay_nos
我们如何在 r 中做到这一点?
我的解决方案使用了一个脏的 for 循环,但产生了所需的指示......希望适合你吗?
bay_no <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
bay_cont <- c(45,25,25,0,19,61,2,134,5,27,0,54,102,97,5,6,65,47,85,0)
count <- 3
bay_to_serve <- sum(bay_cont)/count
temp_sum=0
for (i in 1:(length(bay_cont)-1)) {
temp_sum=temp_sum+bay_cont[i]
if ( abs(bay_to_serve-temp_sum)<abs(bay_to_serve-(temp_sum +bay_cont[i+1]))) {
print(i)
temp_sum=0
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句