R语言ltm包下匹配因子得分模式返回预期案例数的函数实现
R语言IRT建模匹配作答模式预期数量自定义函数
需求
在R语言开展IRT建模的场景中,需要实现自定义函数,输入为因子得分结果对象和目标作答模式,返回匹配该模式的预期案例数量。
基础示例代码
item1 <- cbind(1,0,1,0,1,1,0,0,0,0,1,0) item2 <- cbind(0,0,0,1,0,1,0,1,0,0,1,0) item3 <- cbind(1,0,1,0,1,1,0,1,1,0,0,0) item4 <- cbind(0,0,1,1,0,1,0,0,0,1,1,1) Items <- matrix(c(item1, item2, item3, item4), ncol=4) library(ltm) fit <- ltm(Items ~ z1, IRT.param=TRUE) mle <- ltm::factor.scores(fit,method="EB",prior=FALSE) pattern_of_interest <- c(0,0,0,1)
因子得分结果样例
调用ltm::factor.scores后输出的score.dat结构如下:
Item 1 Item 2 Item 3 Item 4 Obs Exp z1 se.z1 1 0 0 0 0 2 1.948 -96.517 12529.631 2 0 0 0 1 2 1.706 -2.303 3.647 3 0 0 1 0 1 0.744 -0.076 0.303 4 0 1 0 1 1 0.668 -0.864 1.494 5 0 1 1 0 1 0.333 -0.052 0.261 6 1 0 1 0 2 1.051 1.173 1.711 7 1 0 1 1 1 1.225 1.844 2.575 8 1 1 0 1 1 0.199 0.323 0.297 9 1 1 1 1 1 0.834 93.748 10003.995
自定义函数实现
get_expected_count <- function(mle_obj, target_pattern) { # 提取所有题目作答列 pattern_cols <- mle_obj$score.dat[, grepl("^Item", colnames(mle_obj$score.dat))] # 校验目标模式长度与题目数一致 if(length(target_pattern) != ncol(pattern_cols)) { stop("目标作答模式长度与题目数量不匹配") } # 匹配完全一致的作答模式行 match_row <- apply(pattern_cols, 1, function(row_vals) all(row_vals == target_pattern)) # 返回对应预期值,无匹配时返回NA并告警 if(sum(match_row) == 0) { warning("无匹配的作答模式") return(NA_real_) } return(mle_obj$score.dat$Exp[match_row]) }
函数调用示例
get_expected_count(mle, c(0,0,0,1)) # 输出结果:1.706
内容的提问来源于stack exchange,提问作者Madamadam
相关产品推荐
相关产品推荐

