Solved – rbinom() produces NA values. What’s wrong

binomial distributionmissing datarrandom-generation

I have to generate a random variable from a binomial distribution with R. I have a vector for n and a vector for p and for each component I have to generate a random variable. My idea was the following for the code was the following:

X <- vector(mode="numeric")
for (i in 1:25)
{  
    X[i] <- rbinom(1, n[i], p[i])
}

It seems that my thinking is correct but the vector produced, X, contains only NA. I don't know what the problem is. Maybe I have a problem in the dataset? The vectors n and p are the following:

n <- c(0.8888889, 1.6363636, 0.3333333, 0.6153846, 0.4000000, 0.0625000, 0.2857143,
       0.6153846, 0.0000000, 0.2857143, 0.3333333, 0.1250000, 0.8888889, 0.3333333, 
       0.3333333, 0.0000000, 0.0000000, 0.0000000, 0.6000000, 0.1250000, 0.4000000, 
       0.4000000, 0.0000000, 0.6000000, 1.0000000) 
p <- c(0.8019377, 0.7471281, 0.7673853, 0.7302029, 0.6915447, 0.8211286, 0.7725188, 
       0.7077241, 0.7957015, 0.7893677, 0.7585554, 0.7749553, 0.7570536, 0.6159425, 
       0.7717002, 0.7462224, 0.7349991, 0.7486309, 0.7357340, 0.6850625, 0.7468344, 
       0.7967847, 0.6738766, 0.7122724, 0.7791634)

Best Answer

R expects the second argument of rbinom, size, to be an integer, in accordance with the definition of the binomial distribution. So using a number like 0.9 for size produces NA.

Incidentally, your first code block can be written in one line as X <- rbinom(25, n, p).

Related Question