vendredi 1 janvier 2021

A For loop to replace vector value

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

Aucun commentaire:

Enregistrer un commentaire