Correlated Coin Flips in R

I want to simulate coin flips such that:

  • If heads, then next head with p = 0.6 and tail = 0.4
  • if tails, the next tails with p = 0.6 and heads = 0.4

Using the 'markovchain' package in R, I did this as follows:

library(markovchain)

# transition matrix
P <- matrix(c(0.6, 0.4, 0.4, 0.6), byrow = TRUE, nrow = 2)
rownames(P) <- colnames(P) <- c("H", "T")


mc <- new("markovchain", states = c("H", "T"), transitionMatrix = P)

# Generate states
set.seed(123)  # for reproducibility
states <- rmarkovchain(n = 100, object = mc, t0 = "H")

# Print 
table(states)

The output looks something like this:

> states
  [1] "H" "T" "T" "H" "T" "T" "T" "H" "H" 

My Question: Can someone please show me how I can do this in base R?

I think I need to:

  • create an empty list of size "n"
  • assign n[1] = H or T with prob 0.5
  • write an IFELSE statement that says n[i] = ifelse(n[i-1] == "H", sample(c("H", "T"), prob = c(0.6, 0.4), sample(c("H", "T"), prob = c(0.4, 0.6))

But I am not sure how to do this.

Can someone please show me how to do this?

Thanks!

my_flipper <- function(num_to_do,
                       poss = c("H", "T"),
                       probs = c(.6, .4)) {
  results <- character(num_to_do)
  results[1] <- sample(poss, size = 1)

  for (i in 2:num_to_do) {
    p <- probs
    if (results[i - 1] != poss[1]) {
      p <- rev(probs)
    }
    results[i] <- sample(poss,
      size = 1,
      prob = p
    )
  }
  results
}

my_flipper(num_to_do = 100)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.