Search code examples
rmontecarloreplicate

use of curly brackets within replicate function in R


B <- 10000
results <- replicate(B, {
  hand <- sample(hands1, 2)
  (hand[1] %in% aces & hand[2] %in% facecard) | (hand[2] %in% aces & hand[1] %in% facecard)
})
mean(results)

this piece of code works perfectly and do the desired thi
this is a monte carlo simulation. I don't understand the way they put curly brackets {} in the replicate function. i can understand the function of that code but i cant understand the way they put the code.


Solution

  • The reason is that we have multiple expressions

    hand <- sample(hands1, 2)
    

    is the first expression and the second is

     (hand[1] %in% aces & hand[2] %in% facecard) | (hand[2] %in% aces & hand[1] %in% facecard)
    

    i.e. if there is only a single expression, we don't need to block with {}

    It is a general case and not related to replicate i.e. if we use a for loop with a single expression, it doesn't need any {}

    for(i in 1:5)
       print(i)
    

    and similarly, something like if/else

    n <- 5
    if(n == 5) 
      print(n)
    

    It is only needed when we need more than one expression