0

我想在 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循环只尝试一次循环?

4

1 回答 1

0

您尝试设置p为向量,我猜该向量的第一个元素不是您认为的那样。

fit <- lm(sr ~ ., data = LifeCycleSavings)
anova(fit)
fit0 <- lm(sr ~ 1, data = LifeCycleSavings)
fit1 <- update(fit0, . ~ . + pop15)
p <- anova(fit0, fit1, test = "F")

> str(p)
Classes ‘anova’ and 'data.frame':   2 obs. of  6 variables:
 $ Res.Df   : num  49 48
 $ RSS      : num  984 780
 $ Df       : num  NA 1
 $ Sum of Sq: num  NA 204
 $ F        : num  NA 12.6
 $ Pr(>F)   : num  NA 0.000887

如果您的if()命令遇到该值,它将仅评估 NA 值,失败并传递给else子句并退出。

于 2013-10-03T02:28:05.337 回答