0
$\begingroup$

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)
percent_heads <- length(which(flips== "heads")) / n
return(percent_heads)
}

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)
  percent_heads[i] <- length(which(flips == "heads")) / 100
  counter = counter + 1
  }
return(sum(length(which(percent_heads == .4)) / n
}

Any help would really be appreciated. Thanks!

$\endgroup$
0
$\begingroup$

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
percent_heads <- numeric(10000)
counter = 0
for(i in 1:n){
    flips <- sample(c("heads", "tails"), 100, replace=TRUE)
    percent_heads[i] <- length(which(flips == "heads")) / 100
    counter = counter + 1
}
sum(length(which(percent_heads == .4))) / n

which returns about the expected 0.01.

$\endgroup$
2
  • $\begingroup$ 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 $\endgroup$
    – Michael
    Apr 12 '19 at 1:07
  • $\begingroup$ 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! $\endgroup$
    – Mr. Wayne
    Apr 12 '19 at 1:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.