Q:

An algorithm in r about binomial random variables

I have the following algorithm (based on this algorithm)

Generate U
Define x=0,P=(1-p)^n and F=P
If U < F,then X=x and stop.
Define P=(n-x)pP/(x+1)(1-p), F=F+P and x=x+1
Come back to step 3.

According to my knowledge, on r would be 
varBinom<-function(n,p)
{
  U<-runif(n)
  x<-0
  P<-(1-p)^n
  FF<-P

  for(i in 1:n)
  {
    if(U<FF)
    {
      X<-x
      break
    }
    P<-(n-x)*p*P/(x+1)*(1-p)
    FF<-FF+P
    x<-x+1
  }
  return(x)
}

However, when compiling the code, I get ten warning messages all of them say:

Warning messages: 1: In if (U < FF) { :   the condition has length > 1
  and only the first element will be used

Why does that happen?
How can I fix the code?

A:

I think you made two little mistakes.

In 4 it should be P=(n-x) * p * P / ((x+1)*(1-p)) so (1-p) is in the denominator not in the numerator.
U is a one random number, but you create n different random numbers using runif(n). This is also why you get the warning.

So here is the corrected algorithm:
varBinom<-function(n, p)
{
  U <- runif(1)
  x <- 0
  P <- (1-p)^n
  FF <- P

  for(i in 1:n)
  {
    if(U<FF) return(x)
    P <- (n-x) * p * P/((x+1)*(1-p))
    FF <- FF+P
    x <- x+1
  }
  return(x)
}

Here is the result when you call the function 15 times:
set.seed(1)
replicate(15, varBinom(10, 1/2))
[1] 4 4 5 7 4 7 7 6 6 3 4 4 6 5 6

