Home > front end >  R studio - solve: Bernoulli random variable X = 1 if we get a head with probability p and X = 0 if w
R studio - solve: Bernoulli random variable X = 1 if we get a head with probability p and X = 0 if w

Time:02-27

I need help with coding this into R. I'm not well versed with R's library functions.

Given - Let X be a Bernoulli random variable which is defined as X = 1 if we get a head with probability p ## and X = 0 if we get a tail with probability 1 − p.

##This is what I have so far. Not sure if I'm taking the right way in doing this
p = runif(1,0,1)
  if (p<0.5){
    X=1
  } else {
    X=0
  }
print(p); print(X)


## Calculate E(2X)
E(2X) = E(X)*2 = 2p

## Calculate var(3X   4)

## Calculate cov(3X, 5)

## Calculate cov(4X, 6X   1000)

CodePudding user response:

There is a built in function rbinom(n,size, prob) that can be utilized to return a vector of zeroes and ones of length n if size=1. Alternatively, you can mimic this following the logic that you started above, if you like, doing something like this

Your logic, using uniform distribution

flip_coin_n_times_with_head_prop_p <- function(n,p) {
  uniforms = runif(n,0,1)
  heads = sum(uniforms<=p)
  return(heads)
}

Using R's built in rbinom()

built_in_flip <- function(n,p) {
  heads=sum(rbinom(n,1,p))
  return(heads)
}

Now, you can see that these are equivalent, by flipping a coin with probability 0.3, 10000 times:

> flip_coin_n_times_with_head_prop_p(10000,.3)
[1] 2967
> built_in_flip(10000,.3)
[1] 3058

Of course, you may want the sequence of flips themselves.. Either function can be adapated, but I've gone with the built_in_flip() for illustration purposes.

Add parameter return_trials, default is TRUE; will return the sequence of flips by default, but set to FALSE to get the number of heads

built_in_flip <- function(n,p, return_trials=T) {
    trials = rbinom(n,1,p)
    if(return_trials) return(trials)
    else return(sum(trials))
}

Now, when we call this function we get the sequence of flips

built_in_flips(n=10, p=0.5)
[1] 1 1 0 0 1 0 0 0 0 1

We can assign a long sequence of flips to X like this, and then take the mean(X) or the mean(2*X)

X = built_in_flips(10000,0.3, return_trials=T)

# "Expectation of X"
mean(X)
[1] 0.3026

# "Expectation of 2X"
mean(2*X)
[1] 0.6052
  •  Tags:  
  • r
  • Related