0

I have 100000 exponential random variables generated withrexp and I am asked to generate 100000 binomial random variables from them using built in R functions.

I really don't know how can I generate one random variable from another. I searched some resources on internet but they were mostly about generating poisson from exponential which are very related because exponential distribution can be interpreted as time intervals of poisson. making poisson can be easily achieved by applying cumsum on exponentials and using cut function to make some bins including number of occurrences in a time interval.

But I don't know how is it possible to generate binomial from exponential.

amir na
  • 217
  • 1
  • 8
  • Exponential random variables are heavily used in [Poisson processes](https://en.wikipedia.org/wiki/Poisson_point_process) (continuous time) while binomials are often used in [Bernoulli processes](https://en.wikipedia.org/wiki/Bernoulli_process) (discrete time). Are you sure you're supposed to be using exponential and binomial together? – ClancyStats Nov 11 '19 at 18:31
  • To elaborate a bit.. A binomial distribution assumes that you have a set number of trials. The problem with continuous arrival times (exponential) is that for any given interval, the set of possible values for the number of arrivals is all non-negative integers. It doesn't have a set number of trials. – ClancyStats Nov 11 '19 at 18:34
  • @ClancyStats Yes. That's why I am completely confused. because this two are not really related. – amir na Nov 11 '19 at 18:37
  • @ClancyStats But Yes. I am pretty sure that's what it wants. The question is actually two parts. the first part want us to simply make 100000 exponential random variables. the second part wants to convert those exponentials into binomial (using a function made up of only r built in functions - without using for loops) – amir na Nov 11 '19 at 18:42

1 Answers1

1

The function rbin below generates binomial rv's from exponential rv's. The reason why might be a question for CrossValidated, not for StackOverflow, which is about code.

rbin <- function(n, size, p){
  onebin <- function(i, size, thres){
    I <- 0L
    repeat{
      S <- sum(rexp(I + 1)/(size + 1 - seq_len(I + 1)))
      if(S > thres) break
      I <- I + 1L
    }
    I
  }
  thres <- -log(1 - p)
  sapply(seq_len(n), onebin, size, thres)
}


set.seed(1234)
u <- rbin(100000, 1, 0.5)
v <- rbinom(100000, 1, 0.5)

X <- cbind(u, v)
cbind(Mean = colMeans(X), Var = apply(X, 2, var))
#     Mean       Var
#u 0.50124 0.2500010
#v 0.49847 0.2500002
Rui Barradas
  • 44,483
  • 8
  • 22
  • 48