简单回归的R循环

简单回归的R循环,r,regression,R,Regression,我想创建一个可以处理任何数据帧的函数,最小列数为1,最大列数为n。函数必须对每个自变量进行简单的线性回归。我知道我必须使用循环,但我不知道如何使用它。 我试过这个,但不起作用: >data1<-read.csv(file.choose(),header=TRUE,sep=",") >n<-nrow(data1) >PredictorVariables <- paste("x", 1:n, sep="") >Formula <-paste("y ~

我想创建一个可以处理任何数据帧的函数,最小列数为1,最大列数为n。函数必须对每个自变量进行简单的线性回归。我知道我必须使用循环,但我不知道如何使用它。 我试过这个,但不起作用:

>data1<-read.csv(file.choose(),header=TRUE,sep=",")
>n<-nrow(data1)
>PredictorVariables <- paste("x", 1:n, sep="")
>Formula <-paste("y ~ ", PredictorVariables, collapse=" + ",data=data1)
>lm(Formula, data=data1)
这里是一种使用mtcars数据集的Lappy方法。我们将选择MPG作为因变量,从数据集中提取剩余的列,然后使用lapply对indepVars向量中的每个元素运行回归模型。每个模型的输出保存到一个列表中,包括自变量的名称以及生成的模型对象

indepVars <- names(mtcars)[!(names(mtcars) %in% "mpg")]

modelList <- lapply(indepVars,function(x){
     message("x is: ",x)
     result <- lm(mpg ~ mtcars[[x]],data=mtcars)
     list(variable=x,model=result) 
})

# print the first model
modelList[[1]]$variable
summary(modelList[[1]]$model)
作为对原始海报评论的回应,下面是将上述过程封装到R函数中所需的代码。函数regList采用数据帧名称和因变量字符串,然后继续对传递给函数的数据帧中的每个剩余变量运行因变量回归

regList <- function(dataframe,depVar) {
     indepVars <- names(dataframe)[!(names(dataframe) %in% depVar)]

     modelList <- lapply(indepVars,function(x){
          message("x is: ",x)
          result <- lm(dataframe[[depVar]] ~ dataframe[[x]],data=dataframe)
          list(variable=x,model=result) 
     })
     modelList
}

modelList <- regList(mtcars,"mpg")
# print the first model
modelList[[1]]$variable
summary(modelList[[1]]$model)
可以从各个模型对象中提取各种内容。结果如下:

> modelList <- regList(mtcars,"mpg")
x is: cyl
x is: disp
x is: hp
x is: drat
x is: wt
x is: qsec
x is: vs
x is: am
x is: gear
x is: carb
> # print the first model
> modelList[[1]]$variable
[1] "cyl"
> summary(modelList[[1]]$model)

Call:
lm(formula = dataframe[[depVar]] ~ dataframe[[x]], data = dataframe)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.9814 -2.1185  0.2217  1.0717  7.5186 

Coefficients:
               Estimate Std. Error t value Pr(>|t|)    
(Intercept)     37.8846     2.0738   18.27  < 2e-16 ***
dataframe[[x]]  -2.8758     0.3224   -8.92 6.11e-10 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 3.206 on 30 degrees of freedom
Multiple R-squared:  0.7262,    Adjusted R-squared:  0.7171 
F-statistic: 79.56 on 1 and 30 DF,  p-value: 6.113e-10

>

那么以下内容如何:

首先,我创建一些示例数据:

# Sample data
set.seed(2017);
x <- sapply(1:10, function(x) x * seq(1:100) + rnorm(100));
df <- data.frame(Y = rowSums(x), x);
返回对象lst是lm类11-2+1=10拟合结果的列表。比如说,

lst[[1]];
#
#Call:
#lm(formula = df[, idx.y] ~ df[, i])
#
#Coefficients:
#(Intercept)      df[, i]
#     -5.121       55.100
附言
对于以后的帖子,我建议大家看一看,并提供一个示例,包括示例数据

为什么要使用javascript、android、python和iphone标签?如果你想使用除y之外的所有东西作为预测指标,你可以使用lmy~,data=data1。我使用javascript、android。。。因为我发布问题的标签有问题。lmy~,data=data1不会改变任何东西我在evalpredvars,data,env:objet'y'introvable中仍然有相同的问题,但我需要一个函数来接收以下参数:dataframe,响应变量的列号,最小解释变量列的编号,最大解释变量列的编号。例如:函数1 df,1,2,10 1是响应变量的列,解释变量位于2到10的列(包括2到10的列)。该函数对响应变量和数据帧的解释变量集分别y~x1,y~x2。。。etc返回每个回归的诊断图表2行2列。该函数必须适用于任何作为可归纳参数提交给所有用户的数据帧dataframes@jean-philippe-您在上述评论中的附加内容应包括在您的问题中,以及一份报告中。也就是说,我更新了我的答案,加入了一个R函数,它允许指定数据帧名称和因变量名称,而不是列号。答案可以很容易地调整为使用列号。对不起,我只是R的初学者,对我来说太难了。非常感谢您的帮助。我需要一些更通用的方法,使用列编号来处理任何数据帧中独立变量或独立变量的任何名称。
# Custom function where
#  df is the source dataframe
#  idx.y is the column index of the response variable in df
#  idx.x.min is the column index of the first explanatory variable
#  idx.x.max is the column index of the last explanatory variable
# The function returns a list of lm objects
myfit <- function(df, idx.y, idx.x.min, idx.x.max) {
    stopifnot(idx.x.min < idx.x.max, idx.x.max <= ncol(df));
    res <- list();
    for (i in idx.x.min:idx.x.max) {
        res[[length(res) + 1]] <- lm(df[, idx.y] ~ df[, i]);
    }
    return(res);
}
lst <- myfit(df, 1, 2, 11);
lst[[1]];
#
#Call:
#lm(formula = df[, idx.y] ~ df[, i])
#
#Coefficients:
#(Intercept)      df[, i]
#     -5.121       55.100