Wednesday, 2 October 2013

While Loop in [R]: syntax and keywords

While Loop in [R]: syntax and keywords

I want to implement a forward step-wise regression in R. BFP is a
BodyFatPercentage data set, and I am trying to create a regression model
to predict BODYFAT through step-wise regression. Keep getting an error
with the following code:
dataset <- BFP
alpha <- 0.95
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[2,1] < alpha){
x<- c(x,newx)
indiLeft <- indiLeft[-which(names(indiLeft) == newx)]
counter <- counter +1
next
}
else{
print ('while broken')
print (fmla_sub)
break
}
}
Can anyone figure out why this while loop only attempts the loop once?

No comments:

Post a Comment