【问题标题】:R Loop for Variable Names to run linear regression model用于变量名称的 R 循环以运行线性回归模型
【发布时间】:2018-03-11 14:32:44
【问题描述】:

首先,我对此很陌生,所以我的方法/想法可能是错误的,我已经使用 R 和 R Studio 将 xlsx 数据集导入到数据框中。我希望能够遍历列名以获取所有带有“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]]' 找到)”。如果有人能指出我在正确的方向上,我将非常感激。谢谢。

【问题讨论】:

  • 看看this的问题。然后,如果您仍然需要帮助,请说出来。
  • @RuiBarradas 我尝试了那个代码,但最后是res.models[["mpg~disp"]],我希望它附加所有变量名,例如 [[mpg~disp+x2+x3+.... x18]。

标签: r loops linear-regression modeling


【解决方案1】:

好的,我会发布一个答案。我将以数据集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函数,它就变得非常简单了。

【讨论】:

  • 谢谢!我在我的代码中实现了这一点,效果很好!我用我的前两行而不是你的来获取所有的列,它仍然有效
  • 是否也可以合并摘要?如果不担心
  • @Stick Try do.call(rbind, lapply(smry, [[, "coefficients")).
【解决方案2】:

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

坚持您的代码,这应该可以解决问题。

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

【讨论】:

  • 这个创建的子集只有“Total_Transactions”和“col10”中的最后一个变量
猜你喜欢
  • 1970-01-01
  • 2014-05-08
  • 2023-03-11
  • 2021-07-02
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
相关资源
最近更新 更多