A For loop to replace vector value

自古美人都是妖i 提交于 2021-01-07 02:52:13

问题


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.

This is my input

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)

and then i have this condition:

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

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

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

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

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

else 0

and so i wrote this:

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

The result is

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

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


回答1:


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

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

do it --

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



回答2:


You can use cut/findInterval to divide data in different ranges. You can use the output from findInterval as index to subset mydata.

prediction <- c(0, mydata)[findInterval(random, c(0.81,0.85,0.89,0.93,0.97)) + 1]


来源:https://stackoverflow.com/questions/65536401/a-for-loop-to-replace-vector-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!