R - generate sample that follows a geometric distribution

8k Views Asked by At

I'm having trouble coming up with an algorithm that generates a sample (X1,...,Xn) of size n, considering several values for n, where the random variable Xi – “number of trials until the first success ” follows a geometric distribution:

f (x) = 0.7 exp(x-1) 0.3 , x =1, 2,L 

i'm trying to implement this in R (without using rgeom) via the inverse transform method.

Can you help me?

1

There are 1 best solutions below

2
On BEST ANSWER

I think this should do the trick. I used the sample function to draw 0 or 1 with probability $p$ at each trial.

This then corresponds to the pmf given by $$ p(x)=(1-p)^{x-1}p, \quad x=1, 2,\dots $$

n <- 1000   # Sample size
p <- 0.1    # Success probability
X <- c()    # Empty vector for storage


## 0 is a success (stops the loop)
## 1 is a failure (loop continues)
for (i in c(1:n)) {
  temp <- 1 # A temporary variable to store the trial number
  repeat {  # Sample 0 with prob. p, if 0 then stop
    sample <- sample(c(0, 1), 1, prob = c(p, 1-p))
      if (sample == 1) {
        temp <- temp + 1 # Add 1 if failure (go on to next draw)
      } else {
        break
      }
  }
  X <- c(X, temp)
}

Using the inverse transform method, the following seems to work:

n <- 1000   # Sample size
p <- 0.1    # Success probability
X <- c()    # Empty vector for storage

## Create a cumulative mass function
cdf <- function(p, k) {
  cum.prob <- 0
  for (i in 1:k) {
    if (k == 0) {
      cum.prob <- 0
      return(cum.prob)
      break
    }
    cum.prob <- cum.prob + p*(1-p)^(i-1)
  }
  return(cum.prob)
}

iteration <- 0
repeat{ 
  iteration <- iteration + 1
  u <- runif(1) ## Generate a U(0,1) value
  i <- 0

  repeat {      ## Find which x satisfies F(x)<=u<=F(x+1)
    if (cdf(p, i) <= u) {
      if (u <= cdf(p, i + 1)) {
        X <- c(X, i)
        break
      }  
    }
    i <- i + 1
  }

  if (iteration == n) {
    break
  }
}