Skip to content

Instantly share code, notes, and snippets.

@daob
Created August 1, 2017 18:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daob/883fbffdff6762c3bb90b3d8d3d0ae6e to your computer and use it in GitHub Desktop.
Save daob/883fbffdff6762c3bb90b3d8d3d0ae6e to your computer and use it in GitHub Desktop.
Calculate Bivariate Residuals (BVRs) for latent class models in R (poLCA)
# Author: Daniel Oberski
# Date: 2017-08-01
# Bivariate residual statistic for latent class analysis
# Calculate the BVR for poLCA objects
# Argument: a poLCA object
# Value: a dist object with BVRs
# Example: bvr(fit)
bvr <- function(fit) {
stopifnot(class(fit) == "poLCA")
ov_names <- names(fit$predcell)[1:(ncol(fit$predcell) - 2)]
ov_combn <- combn(ov_names, 2)
get_bvr <- function(ov_pair) {
form_obs <- as.formula(paste0("observed ~ ", ov_pair[1], " + ", ov_pair[2]))
form_exp <- as.formula(paste0("expected ~ ", ov_pair[1], " + ", ov_pair[2]))
counts_obs <- xtabs(form_obs, data = fit$predcell)
counts_exp <- xtabs(form_exp, data = fit$predcell)
bvr <- sum((counts_obs - counts_exp)^2 / counts_exp)
bvr
}
bvr_pairs <- apply(ov_combn, 2, get_bvr)
# names(bvr_pairs) <- apply(ov_combn, 2, paste, collapse = "<->")
attr(bvr_pairs, "class") <- "dist"
attr(bvr_pairs, "Size") <- length(ov_names)
attr(bvr_pairs, "Labels") <- ov_names
attr(bvr_pairs, "Diag") <- FALSE
attr(bvr_pairs, "Upper") <- FALSE
bvr_pairs
}
@AGSCL
Copy link

AGSCL commented Nov 5, 2020

When I use it I get a matrix of NaNs. I'm investigating this problem, and is mainly caused in the line 24. I get many Infinite values. I don't know if it is useful to introduce: bvr[is.infinite(bvr)]<-NA; bvr <- sum(bvr,na.rm=T)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment