dlinzer / poLCA

Polytomous Variable Latent Class Analysis (R package)
https://dlinzer.github.io/poLCA/
48 stars 17 forks source link

bad starting values when nrep>1 #15

Open adamSales opened 6 years ago

adamSales commented 6 years ago

I came across an issue, and wrote a small hack to circumvent it that seems to work--here goes:

When running a model with nrep>1, I'll sometimes get output that looks like this:

... Model 78: llik = -22780 ... best llik = -19583 Model 79: llik = -21839 ... best llik = -19583 Error in poLCA:::poLCA.ylik.C(vp, y) : NA/NaN/Inf in foreign function call (arg 1)

I'm not entirely sure what the error is, but (since the model fit the first 79 times) I assume it has to do with bad randomly-chosen starting values. In this situation, I'd rather the software just discard the bad result and move on, rather than crash entirely. By tweaking the poLCA code as follows, it does just that. First, a little function (I bet there's a more elegant way of doing this):

tryNA <- function(x){
    x <- try(x)
    if(inherits(x,'try-error')) return(NA)
    x
}

the replace the line

llik[iter] <- sum(log(rowSums(prior *poLCA.ylik.C(vp,`
                    y))))

with

llik[iter] <- tryNA(sum(log(rowSums(prior *poLCA.ylik.C(vp,
                      y)))))

and now everything seems to work just fine.