I am working with the rnbinom
function in R but I think I have misunderstood the meaning of the parameters that get stipulated in the arguments.
For reference, I have been looking at the documentation here: https://stat.ethz.ch/R-manual/R-devel/library/stats/html/NegBinomial.html
I have generated a random vector like so:
z <- rnbinom(500000, 0.16, 0.19)
My understanding is that I have called for 500000
random values from a negative binomial distribution with a dispersion (theta) parameter of 0.16
. For the prob
argument I entered 0.19
, which is defined as "probability of success in each trial. 0 < prob <= 1." I have interpreted this argument as setting an "effect size" that would be returned if the simulated data is fit back into a negative binomial regression model. However, my understanding is evidently wrong. Please see the below for a step-by-step.
Load libraries
library(ggplot2)
library(reshape2)
library(MASS)
When I plot the vector it looks like this:
hist(z)
Based on this histogram, the randomly generated vector is then transformed into a 2-column dataframe where the original values act as Xs and the frequencies act as Ys, like so:
dat <- data.frame(z=z,freq=as.vector(table(z)[as.character(z)]))
Rename columns:
colnames(dat) <- c("X","Y")
Plotting this X-Y dataframe looks like this:
g1 <- ggplot(dat, aes(x = z, y = freq))+
geom_point(alpha = .2)+
theme_bw()+
labs(x = "X", y = "Y")
g1
Then, I attempt to fit this dataframe back into a negative binomial regression model:
M0 <- glm.nb(Y ~ X, data = dat)
summary(M0)
But I get this error:
Error: no valid set of coefficients has been found: please supply starting values
In addition: Warning message:
glm.fit: fitted rates numerically 0 occurred
What is happening here? I had expected the model to return a regression coefficient of 0.19
as I stipulated in the original random vector generation.
dat
? Trydat <- data.frame(z=z,freq=as.vector(table(z)[as.character(z)]))
. $\endgroup$