# Simulate multispecies data
M <- 300
J <- 5
S <- 30
set.seed(123)
x <- rnorm(M)
mu_0 <- 0
sd_0 <- 0.4
beta0 <- rnorm(S, mu_0, sd_0)
mu_x <- 1
sd_x <- 0.3
beta_x <- rnorm(S, mu_x, sd_x)
mu_a <- 0
sd_a <- 0.2
alpha0 <- rnorm(S, mu_a, sd_a)
ylist <- list()
z <- matrix(NA, M, S)
for (s in 1:S){
psi <- plogis(beta0[s] + beta_x[s] * x)
z[,s] <- rbinom(M, 1, psi)
p <- plogis(alpha0[s])
y <- matrix(NA, M, J)
for (m in 1:M){
y[m,] <- rbinom(J, 1, p * z[m,s])
}
ylist[[s]] <- y
}
names(ylist) <- paste0("sp", sprintf("%02d", 1:S))
# Create unmarkedFrame
sc <- data.frame(x=x, a=factor(sample(letters[1:5], M, replace=TRUE)))
umf <- unmarkedFrameOccuComm(ylist, siteCovs=sc)
# \donttest{
# Fit model with one covariate on occupancy
(fit <- occuComm(~1~x, umf))
# Look at species-specific random intercepts and slopes
rt <- randomTerms(fit, addMean = TRUE)
head(rt)
# Compare true and estimated random occupancy intercepts
beta0_est <- subset(rt, Model == "psi" & Name == "(Intercept)")$Estimate
plot(beta0, beta0_est, xlab="truth", ylab="estimate", pch=19,
main="Random occ intercepts")
abline(a=0, b=1, col='red')
# Estimate richness for each site
r <- richness(fit)
# Compare true and estimated richness
plot(r, apply(z, 1, sum), xlab="estimate", ylab="truth", main="Richness")
abline(a=0, b=1)
# }
Run the code above in your browser using DataLab