Created
August 1, 2017 18:26
-
-
Save daob/883fbffdff6762c3bb90b3d8d3d0ae6e to your computer and use it in GitHub Desktop.
Calculate Bivariate Residuals (BVRs) for latent class models in R (poLCA)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)