2
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.

1 Answers1

3

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

akrun
  • 874,273
  • 37
  • 540
  • 662
  • So the value passing to the replicate function is the value of the second expression. Am i right. – Nadika Dushan Aug 01 '21 at 19:42
  • @NadikaDushan It is multiple expression and the value you returned is from the last expression evaluated. The first expression is just `sample`ing which is the main difference in each of the iteration in `replicate` – akrun Aug 01 '21 at 19:43