一个For循环来替换向量值 [英] A For loop to replace vector value

查看:68
本文介绍了一个For循环来替换向量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我的代码有什么问题.基本上,我正在尝试做蒙特卡罗模拟的小版本.

I couldn't figure out what's the problem on my code. Basically i'm trying to do a small version of Monte Carlo simulation.

这是我的输入

mydata=[1,4,20,23,37]
prediction=c(0,0,0,0,0,0,0,0,0,0,0,0)
randomvar=runif(12,0,1)

然后我有这种情况:

如果 randomvar 的第i个值是>0.97,将 prediction 的第i个值替换为 mydata

if i-th value of randomvar is > 0.97, replace i-th value of prediction with 5th data from mydata

否则,如果 randomvar 的第i个值是>0.93,将 prediction 的第i个值替换为 mydata

else if i-th value of randomvar is > 0.93, replace i-th value of prediction with 4th data from mydata

否则,如果 randomvar 的第i个值是>0.89,将 prediction 的第i个值替换为 mydata

else if i-th value of randomvar is > 0.89, replace i-th value of prediction with 3rd data from mydata

否则,如果 randomvar 的第i个值是>0.85,用来自 mydata

else if i-th value of randomvar is > 0.85, replace i-th value of prediction with 2nd data from mydata

否则,如果 randomvar 的第i个值是>0.81,将 prediction 的第i个值替换为 mydata

else if i-th value of randomvar is > 0.81, replace i-th value of prediction with 1st data from mydata

其他0

所以我写了这个:

mydata=c(1,4,20,23,37)
prediction=c(0,0,0,0,0,0,0,0,0,0,0,0)
random=runif(12,0,1)
for (i in random) {
  if (i>0.97) prediction[i]=mydata[5]
  else if (i>0.93) prediction[i]=mydata[4]
  else if (i>0.89) prediction[i]=mydata[3]
  else if (i>0.85) prediction[i]=mydata[2]
  else if (i>0.81) prediction[i]=mydata[1]
  else prediction[i]=0
}
prediction

结果是

> prediction
 [1] 0 0 0 0 0 0 0 0 0 0 0 0

我想知道为什么代码不会根据上述条件更改预测值.有人可以帮忙解释一下吗?反正我还是R的新手

I wonder why the code won't change the prediction value based on the condition above. Could anyone help and explain why? I'm new to R anyway

推荐答案

该代码无法正常工作,因为使用 runif 生成的随机值不是整数.

The code is not working because, random values generated using runif are not integers.

> random=runif(12,0,1)
> random
 [1] 0.78381826 0.97424261 0.87240491 0.20896106 0.95598721 0.11609102 0.02430861
 [8] 0.24213124 0.45808710 0.28205870 0.51469212 0.02672362

现在 prediction [i] (其中 i 位于 random 中)毫无意义.

Now prediction[i] where i is in random is meaningless.

做到-

for (i in seq_along(random)) {
  if (random[i]>0.97) prediction[i]=mydata[5]
  else if (random[i]>0.93) prediction[i]=mydata[4]
  else if (random[i]>0.89) prediction[i]=mydata[3]
  else if (random[i]>0.85) prediction[i]=mydata[2]
  else if (random[i]>0.81) prediction[i]=mydata[1]
  else prediction[i]=0
}
prediction
> prediction
 [1]  0  0  0  0 20  4  0  0  0  0  0  0

这篇关于一个For循环来替换向量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆