Antoni Parellada
Antoni Parellada

Reputation: 4791

Hot Hand Fallacy: R Code to Reproduce Simulation

BACKGROUND:

As a follow-up of my preceding question, I would like to ask for help reproducing a more intricate result on the original paper quoted by an opinion column in The New York Times yesterday. In that paper originated in Milan and Alicante, an interesting reduction in the frequency by which a Head was followed by another head (~ 40%) was presented. The simulation in the SO question this morning was concordant after solved by @Roland.

QUESTION"

The question is how to code in R a simulation to reproduce the fraction of successes ("heads") in a coin toss that follow a sequence of successes (k successes) in short coin toss experiment (n tosses), as in the plot included below, which belongs to an article linked in the "background" part of the question.

enter image description here

Upvotes: 2

Views: 295

Answers (1)

alexwhitworth
alexwhitworth

Reputation: 4907

Here's a simple solution:

#' @param n An integer giving the number of trials
#' @param k An integer giving the prior-streak size.
#' @examples 
#' repeat_success(10,2)
#' repeat_success(100, 5)

repeat_success <- function(n,k) {
  path <- sample(c(1,0), size= n, replace= TRUE)
  successes <- which(path == 1)

  streaks <- rep(0, length(successes))
  for (i in 1:length(successes)) {
    j <- successes[i]
    if (j > k)
      streaks[i] <- ifelse(sum(path[(j-k):(j-1)]) == k, 1, 0)
  }
  return(list(successes= successes, frac_streaks= sum(streaks) / sum(path)))
}

R> repeat_success(10,2)
$successes
[1] 1 3 5 8 9

$frac_streaks
[1] 0

Obviously, you could set a seed for reproducibility. And clearly I haven't included error checking on the parameters.

Upvotes: 2

Related Questions