Search code examples
rfor-loopif-statementmontecarlo

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


Solution

  • 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