# Monte Carlo Sim for Coin Toss in R [closed]

I'm trying to answer the following simple probability question but using a monte carlo type simulation function in R: A fair coin is flipped 100 times. Find the probability that the number of times it shows heads is exactly equal to 40.

I'm pretty new to simulations and to writing functions in R, so I'm at a lot of a loss.

I know I can do this to simulate finding the percent heads flipped in a given sample of coin tosses:

    flip_function <- function(n) {
flips <- sample(c("heads", "tails"), n, replace=TRUE)
}


I know I'll need to use a for loop but my best guess is just wrong (in fact it returns an error saying I have an excessive } which I also don't understand):

counter = 0
flip_function <- function(n){
for(i in 1:n){
flips <- sample(c("heads", "tails"), 100, replace=TRUE)
counter = counter + 1
}
}


Any help would really be appreciated. Thanks!

Do you have the vector percent_heads initialized elsewhere? If you mean to have it completely contained within the function it must be initialized outside the for loop. I took your code outside the function and it seems to work okay with some minor changes (your return statement is missing 2 brackets -- likely the source of your error).

n <- 10000
counter = 0
for(i in 1:n){
flips <- sample(c("heads", "tails"), 100, replace=TRUE)
counter = counter + 1
}


which returns about the expected 0.01.

• Is it the case that one always needs the vector/matrix one is filling to be initialized outside? I'm guessing yes because that would make sense, but it would be wonderful to have someone more knowledgable confirm for me. edit: and thanks for letting me know about the bracks for the return statement. I think I got so frustrated working on this simple function for 2 hours that I couldn't even do a basic count of them. lol Commented Apr 12, 2019 at 1:07
• Well, if you had initialized it within the loop it would be reset upon each iteration. Of course everything depends on the problem at hand. If the answer works for you please don't forget to accept it. Thanks! Commented Apr 12, 2019 at 1:19