'Coin flip probability

I'm wondering what I should be doing here (please refer to image). I have already defined two vectors which are k=c(0,1) and v=c(runif(2,0.3,0.7)) where alpha=v[1] and beta=v[2]. Afterwards, I used an if statement, if(Xn==k[1]){...} However this is where I am stuck at. According to the question, I have to assign Xn+1=k[1] with probability (alpha) at the same time Xn+1=k[2] with probability (1-alpha) and if(Xn==k[2]){...} then Xn+1=k[1] has probability (beta) and Xn+1=k[2] will have probability (1-beta).

So my question is how do you assign the values to the respective Xn+1 values of 0 and 1 with probabilities [(alpha), (1-alpha)] and [(beta),(1-beta)]. After assigning it, how do you then run a simulation of 500 observations from X1 to X500 of the random variable by using a for loop This is similar to the coin toss experiment with the exception being that probability of Heads and Tails are decided by [alpha,beta] = runif(2,0.3,0.7)`.



Solution 1:[1]

Here is a base R solution.

toss <- function(n = 500L){
  a <- runif(2, min = 0.3, max = 0.7)
  alpha <- a[1]
  beta <- a[2]
  x <- integer(n)
  x[1] <- rbinom(1, size = 1, prob = alpha)
  for(i in seq_len(n - 1)){
    if(x[i] == 0)
      x[i + 1L] <- rbinom(1, size = 1, prob = 1 - alpha)
    else
      x[i + 1L] <- rbinom(1, size = 1, prob = 1 - beta)
  }
  list(x = x, alpha = alpha, beta = beta)
}

set.seed(2021)
X <- toss()
table(X$x)
#
#  0   1 
#277 223 
mean(X$x)
#[1] 0.446
X$alpha
#[1] 0.4805069
X$beta
#[1] 0.6135119

Histogram of 1000 runs.

To run the function repeatedly, use replicate.

Y <- replicate(1000, mean(toss()$x))
hist(Y, xlab = "Proportion of successes")

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1