代码之家  ›  专栏  ›  技术社区  ›  Stick

用于运行线性回归模型的变量名的R循环

  •  2
  • Stick  · 技术社区  · 7 年前

    10

    indx <- grepl('_10_', colnames(data)) #list returns all of the true values in the data set
    col10 <- names(data[indx]) #this gives me the names of the columns I want
    

    下面是我的for循环,它返回一个错误:

    temp <- c()
    for(i in 1:length(col10)){
       temp = col10[[i]]
      lm.test <- lm(Total_Transactions ~ temp[[i]], data = data)
      print(temp) #actually prints out the right column names
      i + 1
    }
    

    甚至可以运行循环来将这些变量放入线性回归模型中吗?我得到的错误是:“model.frame.default(formula=Total_Transactions~temp[[I]],:变量长度不同(为“temp[[I]]”找到)”。如果有人能为我指出正确的方向,我将不胜感激。谢谢

    2 回复  |  直到 7 年前
        1
  •  7
  •   Rui Barradas    7 年前

    好的,我会发布一个答案。我将使用数据集 mtcars 举个例子。我相信它将适用于您的数据集。
    lm.test ,类的对象 list . 在您的代码中,您正在分配 lm(.)
    然后,在循环中,我使用函数 reformulate

    # Use just some columns
    data <- mtcars[, c("mpg", "cyl", "disp", "hp", "drat", "wt")]
    col10 <- names(data)[-1]
    
    lm.test <- vector("list", length(col10))
    
    for(i in seq_along(col10)){
        lm.test[[i]] <- lm(reformulate(col10[i], "mpg"), data = data)
    }
    
    lm.test
    

    现在,您可以将结果列表用于各种事情。我建议你开始使用 lapply
    例如,要提取系数:

    cfs <- lapply(lm.test, coef)
    

    为了获得总结:

    smry <- lapply(lm.test, summary)
    

    一旦你熟悉了 *apply 功能。

        2
  •  2
  •   AshOfFire    7 年前

    您可以创建一个临时子集,在其中仅选择回归中使用的列。这样,您就不需要在公式中注入临时名称。

    for(i in 1:length(col10)){
     tempSubset <- data[,c("Total_Transactions", col10[i]]
     lm.test <- lm(Total_Transactions ~ ., data = tempSubset)
     i + 1
    }