rbchan / unmarked

R package for hierarchical models in ecological research
https://rbchan.github.io/unmarked/
37 stars 25 forks source link

Fix simulate() to work with multinomial distributions when there are missing values #171

Closed kenkellner closed 4 years ago

kenkellner commented 4 years ago

Unlike other random number generators, rmultinom throws errors when dealing with NAs. Added a wrapper around rmultinom to use in simulate methods, so that it just returns NAs instead:

rmultinom2 <- function(n, size, prob){
  if(is.na(size)){
    return(matrix(NA, length(prob), length(n)))
  }
  stats::rmultinom(n=n, size=size, prob=prob)

}

Also, and probably more importantly, fixed a major bug in simulate for unmarkedGDS objects.

Previously:

for(i in 1:M) {
            switch(mixture,
                P = Ns <- rpois(1, lambda[1]), # lambda[1] for all sites!!!!
                NB = {
                    alpha <- exp(coef(object, type="alpha"))
                    Ns <- rnbinom(1, mu=lambda[i], size=alpha)
                    })

Now:

for(i in 1:M) {
            switch(mixture,
                P = Ns <- rpois(1, lambda[i]),
                NB = {
                    alpha <- exp(coef(object, type="alpha"))
                    Ns <- rnbinom(1, mu=lambda[i], size=alpha)
                    })

Fixes #163

rbchan commented 4 years ago

Thanks for catching that bug. We might want to announce it on the Google group because I bet it is one reason why people have been reporting lack of fit.