首页 > 解决方案 > R 使用指数回归方程

问题描述

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

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) 中的错误:公式中的无效功率

标签: r

解决方案


对我来说,问题似乎是公式中的 ^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)
)
}

推荐阅读