Search code examples
rfor-loopmontecarlo

monte carlo simulation error, wont update count


nrep = 1000
count = 0
x = rnorm(n = 30, mean = 20, sd = 3)
y = rnorm(n = 30, mean = 22, sd = 5)

for (i in 1:nrep) {
  a = sample(x, 1)
  b = sample(y, 1)
  if ((a | b) > 25)  count = count + 1
}
print(count/nrep)

When I run this monte carlo simulation it returns 0. If I remove a and b from the loop and use just x and y it takes way too long and returns nothing but the error "The condition has length > 1 and only the first element will be used".

I want it to count the number of times out of 1000 that the larger of a or b is greater than 25.


Solution

  • The logical operation in your 'if' statement is incorrectly specified. When using the OR operator '|' you must have a the logical values you wish to combine on either side of the '|'. The code below shows the proper specification under a commented out version of your 'if' statement.

    Additionally, '|' will return TRUE any time either operand is non-zero. This is because R's '|' operator interprets any non-zero numeric value as TRUE (zero itself is interpreted as FALSE.

    nrep = 1000
    count = 0
    x = rnorm(n = 30, mean = 20, sd = 3)
    y = rnorm(n = 30, mean = 22, sd = 5)
    
    for (i in 1:nrep) {
      a = sample(x, 1)
      b = sample(y, 1)
    
      # if ((a | b) > 25)  count = count + 1
      if (a > 25 | b > 25)  count = count + 1
    }
    print(count/nrep)