我想在 R 中实现前向逐步回归。BFP 是一个 BodyFatPercentage 数据集,我正在尝试创建一个回归模型来通过逐步回归来预测 BODYFAT。不断报错
(错误:break/next 没有循环,跳转到顶层
}}
错误:“}”中出现意外的“}”
使用以下代码:
dataset <- BFP
alpha <- 0.01
namestarget <- 'BODYFAT'
inde <- c('AGE','WEIGHT','HEIGHT','NECK','CHEST','ABDOMEN',
'HIP','THIGH','KNEE','ANKLE','BICEPS','FOREARM','WRIST')
x <- 1
counter <- 0
indiLeft <- as.data.frame(subset(dataset)[inde])
fmla_sub <- NULL
fmla_sup <- NULL
while (TRUE){
print c('starting',counter,newx, indiLeft)
correlations <- cor(dataset[target],indiLeft)
newx <- colnames(correlations)[(which(correlations == max(correlations)))]
fmla_sub <- as.formula(paste(target,"~", paste(x, collapse= "+")))
fmla_sup <- as.formula(paste(target,"~", paste(c(x,newx), collapse= "+")))
p <- anova(lm(fmla_sub,data=dataset),lm(fmla_sup,data=dataset), test="F")['Pr(>F)']
if (p$'Pr(>F)'[2] < alpha){
x<- c(x,newx)
indiLeft <- indiLeft[-which(names(indiLeft) == newx)]
counter <- counter +1
next
}else{
print ('while broken')
print (fmla_sub)
break
}
}
谁能弄清楚为什么这个while循环只尝试一次循环?