我试图在模型选择过程中估计几个对数线性模型。在选择过程中,我首先添加主效应,然后在每个步骤中添加相应的交互效果顺序。为简化起见,我想编写一个循环,它估计对数线性模型并将每个模型保存在列表中
fits <- list()
for (i in (1:3)) {
if (i < 2) {
fits <- loglm(Freq ~ ., data = table.analysis.b)
} else {
fits[i] <- loglm(Freq ~ . + . ^ i, data = table.analysis.b)
}
}
循环中断了相应的错误:
terms.formula(公式,数据=数据)中的错误:无效的电源 式
数据结构与此类似:
trstplt stfgov educ gndr vote Freq
40 5 3 Upper secondary education Male Yes 0.0001
41 1 4 Upper secondary education Male Yes 2.0000
42 2 4 Upper secondary education Male Yes 6.0000
43 3 4 Upper secondary education Male Yes 32.0000
44 4 4 Upper secondary education Male Yes 17.0000
45 5 4 Upper secondary education Male Yes 0.0001
更新 我找到了一个基于此示例的解决方案:http://www.ats.ucla.edu/stat/r/pages/looping_strings.htm
varlist<-c(2,3)
models<-lapply(varlist, function(x){
if (x>1) { loglm(substitute(Freq ~ .^i, list(i = x)), data = table.analysis.b)
} else{
loglm(Freq~., data=table.analysis.b)
}})