################################################################ #This returns a dataframe with the columns ##Int -- cells with 0, 1, 2, etc. ##Freq -- total sample size in that count ##PoisF -- the total count expected via the Poisson distribution ##ResidF -- the residual between Freq and PoisF (count scale) ##Prop -- proportion of the sample with that integer value ##PoisD -- the proportion expected via the Poisson distribution ##ResidD -- residual between Prop and PoisD (proportion scale) CheckPoisson <- function(counts,min_val,max_val,pred){ freqN <- as.data.frame(table(factor(counts,levels=min_val:max_val))) mu <- pred #mean(counts) if(length(mu) == 1){ print( paste0('mean: ', mean(counts)) ) print( paste0('variance: ',var(counts)) ) PoisD <- dpois(min_val:max_val,mu) } else{ PoisD <- min_val:max_val n <- length(counts) for (i in 1:length(PoisD)){ PoisD[i] <- sum(dpois(PoisD[i],mu))/n } } freqN\$PoisF <- PoisD*length(counts) freqN\$ResidF <- (freqN\$Freq - freqN\$PoisF) freqN\$Prop <- (freqN\$Freq/sum(freqN\$Freq))*100 freqN\$PoisD <- PoisD*100 freqN\$ResidD <- (freqN\$Prop - freqN\$PoisD) freqN\$Var1 <- as.numeric(as.character(freqN\$Var1)) names(freqN)[1] <- 'Int' return(freqN) } ################################################################ ##Example use for constant over the whole sample #set.seed(10) #lambda <- 0.2 #x <- rpois(10000,lambda) #CheckPoisson(x,0,max(x),mean(x)) #82% zeroes is not zero inflated -- expected according to Poisson! ##Example use if you have varying predictions, eg after Poisson regression #n <- 10000 #ru <- runif(n,0,10) #x <- rpois(n,lambda=ru) #CheckPoisson(x, 0, 23, ru) ###################### #ToDo, this for negative binomial fit ######################