JenniNiku / gllvm

Generalized Linear Latent Variable Models
https://jenniniku.github.io/gllvm/
48 stars 20 forks source link

Predict fails when both TR and randomX are supplied #74

Closed hrlai closed 1 year ago

hrlai commented 1 year ago

Hi again, also found that predict.gllvm fails with the following:

library(gllvm)

data(antTraits)
y <- as.matrix(antTraits$abund)
X <- scale(antTraits$env[, 1:3])
TR <- (antTraits$tr[, 1:3])
# Fit gllvm model
fit <- gllvm(y = y, X, TR,
             family = poisson(),
             randomX = ~ .)

# Predict new sites:
# Generate matrix of environmental variables for 10 new sites
xnew <- cbind(rnorm(10), rnorm(10), rnorm(10))
colnames(xnew) <- colnames(X)
predfit <- predict(fit, newX = xnew, type = "response", level = 0)

I got Error in xr %*% object$params$Br : non-conformable arguments, which seems to go away if I remove the trait inputs:

# no error below
fit <- gllvm(y = y, X, 
             family = poisson(),
             randomX = ~ .)
xnew <- cbind(rnorm(10), rnorm(10), rnorm(10))
colnames(xnew) <- colnames(X)
predfit <- predict(fit, newX = xnew, type = "response", level = 0)

So we can fit random species slope but can't do prediction when traits are also in the slopes' submodel...

JenniNiku commented 1 year ago

Thanks for noting. This seem to be a bug related to the way the randomX is defined. I will try to fix this. However, you can avoid this error by writing the formula for randomX fully, eg. this should work:

fit <- gllvm(y = y, X, TR, family = poisson(), randomX = ~ Bare.ground+Canopy.cover+Shrub.cover) xnew <- cbind(rnorm(10), rnorm(10), rnorm(10)) colnames(xnew) <- colnames(X) predfit <- predict(fit, newX = xnew, type = "response", level = 0)

hrlai commented 1 year ago

Thank you! Just want to confirm here that this workaround works nicely for the moment. :)

JenniNiku commented 1 year ago

This have been fixed now, in commit e80712b5ffd43b53286ebba4ea2c47030a4b4d65