如何将CSV生成的约束转为MCMCdynamicIRT1d的theta.constraints有效列表?
解决MCMCdynamicIRT1d函数theta.constraints参数报错问题
问题场景
使用R语言MCMCpack包的MCMCdynamicIRT1d函数时,通过CSV衍生的dataframe定义约束:
constraints <- structure(list(state = c("CA", "CA", "CA", "CA"), justice = c("smith", "lee", "bosworth", "dickens"), direction = c("-", "-", "+", "+")), class = "data.frame", row.names = c(NA, -4L))
尝试用paste生成约束列表传入theta.constraints参数时,出现报错:
Error in lambda.constraints[[i]] : attempt to select less than one element in integerOneIndex
但手动输入格式正确的命名列表(list(smith='-', lee='-', bosworth='+', dickens='+'))可正常运行,需修正约束列表的生成方式。
解决方案
函数要求theta.constraints接收命名列表,而非字符串或字符向量。以下两种方法可生成符合要求的约束列表:
方法1:使用setNames快速构造
constraints_list <- setNames(as.list(constraints$direction), constraints$justice)
方法2:循环遍历构造
constraints_list <- list() for (i in seq(nrow(constraints))) { constraints_list[[constraints$justice[i]]] <- constraints$direction[i] }
生成后直接将constraints_list传入theta.constraints参数即可正常运行。
内容的提问来源于stack exchange,提问作者hy9fesh
相关产品推荐
相关产品推荐

