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!