0

我想像这样在循环中使用变量;

for(i_want_to_use_this in seq(1,8)){
lm(
  y ~ (
    PC1 + PC2 + PC3 + PC4 + PC5 + PC6 + PC7 +PC8
  )^i_want_to_use_this ,
  data = as.data.frame(transformed2)
)
}

我已经尝试了很多东西,但我无法做到这一点。有人对此有任何想法吗?

 y ~ PC1 + PC2 + ... + PC8 + PC1:PC2+PC1:PC3+...+PC1:PC8+...+PC1:PC2:..:PC8

多谢。

编辑

我得到以下错误。

terms.formula(formula, data = data) 中的错误:公式中的无效功率

4

2 回答 2

2

对我来说,问题似乎是公式中的 ^1 。

尝试这个:

for(i_want_to_use_this in seq(1,8)){
form = if(i_want_to_use_this < 2) formula("y ~ (PC1 + PC2 + PC3 + PC4 + PC5 + PC6 + PC7 +PC8)") else formula(paste0("y ~ (PC1 + PC2 + PC3 + PC4 + PC5 + PC6 + PC7 +PC8)^",i_want_to_use_this))

lm(form, data = as.data.frame(transformed2))
}

或者,使用您的代码稍作修改:

编辑这个答案:

PC1 + PC2 + PC3 + PC4 + PC5 + PC6 + PC7 +PC8
      )^i_want_to_use_this

this 不能用作公式,因为它用作纯字符串(i_want_to_use_this 不会转换为其数值)。

必须将其粘贴在一起:

paste0("PC1 + PC2 + PC3 + PC4 + PC5 + PC6 + PC7 +PC8
      )^",i_want_to_use_this)

这种方式i_want_to_use_this被它包含的数字所取代

lm(
  y ~ (
    PC1 + PC2 + PC3 + PC4 + PC5 + PC6 + PC7 +PC8
  ),
  data = as.data.frame(transformed2)
)

for(i_want_to_use_this in seq(2,8)){
lm(
  y ~ (
    paste0("PC1 + PC2 + PC3 + PC4 + PC5 + PC6 + PC7 +PC8
  )^",i_want_to_use_this),
  data = as.data.frame(transformed2)
)
}
于 2018-08-31T08:33:03.700 回答
-1

这就是解决方案;

lm(
  paste0("y~(PC1+PC2+PC3+PC4+PC5)^",i),
  data = as.data.frame(transformed2)
)

编辑@jogo

for(i in seq(2,10)){

  abc <-
    model.matrix(lm(
      paste0("y~(anode + augiris + btb + elution + ewc + nacn + naoh + flow + loadcar+ saat_no)^",i),
      data = as.data.frame(saat)
    ))
  x <- (abc[, 2:length(colnames(abc))])

  # print(head(x,2))
  lambdas <- 10 ^ seq(3,-2, by = -.1)
  for (alp in seq(0, 1, 0.01)) {
    cv_fit <- cv.glmnet(x,
                        y,
                        alpha = alp,
                        lambda = lambdas)
    opt_lambda <- cv_fit$lambda.min
    fit <- cv_fit$glmnet.fit
    y_predicted <-
      predict(fit, s = opt_lambda, newx = x)

    # Sum of Squares Total and Error
    sst <- sum((y - mean(y)) ^ 2)
    sse <- sum((y_predicted - y) ^ 2)

    # R squared
    rsq <- 1 - sse / sst


    if (se_last > sse) {
      se_last <- sse
      rsq_son <- rsq
      y_predicted_son <- y_predicted
      y_son <- y
      alp_son<-alp
      fit_son <- fit
      opt_lambda_son <- opt_lambda
      i_son<-i
      print(paste0(i, "-",alp, "-", rsq))
    }
  }
}
于 2018-08-31T08:15:03.323 回答