Created
November 11, 2013 14:17
-
-
Save n8thangreen/7413806 to your computer and use it in GitHub Desktop.
Vector of conditional probabilities from a multinomial logistic regression given particular covariate values
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
probs.logit_covs <- function(groups, cov, data){ | |
## | |
## given a (set of) covariate values, calculates the class membership probabilities | |
## | |
## groups: response field name of interest in NATSAL e.g. het1yr (string) | |
## cov: explanatory covariate name e.g. age_shift (string) | |
## data: e.g. NATSAL.dat (array) | |
## ordered sequence of covariate levels | |
## copy those covered in data but could include intermediate values too | |
cov.seq <- sort(unique(data[,cov])) | |
## vector of group (class) labels for groups | |
## e.g. number of partners | |
grps.seq <- sort(unique(data[,groups])) | |
## include only columns of interest | |
## and create an mlogit input format array | |
head(data0 <- data[,c(groups, cov)]) | |
head(data.long <- mlogit.data(data0, shape="wide", choice=groups), 50) | |
formula.cov <- as.formula(paste(groups, " ~ 0 | ", cov, sep="")) | |
fit.mlogit <- mlogit(formula.cov, data=data.long) | |
coeff <- fit.mlogit$coefficients | |
## calculate individual group probabilities | |
## for a given (set of) covariates | |
## p(X=k) | |
probs.logit <- matrix(NA, ncol=length(grps.seq), nrow=length(cov.seq)) | |
colnames(probs.logit) <- grps.seq | |
rownames(probs.logit) <- cov.seq | |
j <- 0 | |
for (x in cov.seq){ | |
j <- j+1 | |
probs.logit[j,] <- probs.logit(grps.seq, cov, coeff, x) | |
} | |
probs.logit | |
} | |
## END FUNCTION ## |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment