在R中循环多个“多重线性回归" [英] Loop multiple 'multiple linear regressions' in R

查看:124
本文介绍了在R中循环多个“多重线性回归"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库,我想在其中进行多个多元回归.它们都看起来像这样:

I have a database where I want to do several multiple regressions. They all look like this:

fit <- lm(Variable1 ~ Age + Speed + Gender + Mass, data=Data)

唯一的变量更改是variable1.现在,我想循环或使用apply系列中的某些内容在variable1处循环几个变量.这些变量是我的数据文件中的列.有人可以帮我解决这个问题吗?非常感谢!

The only variable changing is variable1. Now I want to loop or use something from the apply family to loop several variables at the place of variable1. These variables are columns in my datafile. Can someone help me to solve this problem? Many thanks!

到目前为止我尝试过的事情:

当我使用names()函数提取列名称之一时,确实得到了列名称:

When I extract one of the column names with the names() function I do get a the name of the column:

varname  = as.name(names(Data[14])) 

但是当我填写此内容时(我使用了attach()函数):

But when I fill this in (and I used the attach() function):

fit <- lm(Varname ~ Age + Speed + Gender + Mass, data=Data) 

我收到以下错误:

model.frame.default中的错误(公式=变量名〜年龄+速度+性别 +:对象不是矩阵

Error in model.frame.default(formula = Varname ~ Age + Speed + Gender + : object is not a matrix

我想lm()函数不能将Varname识别为Variable1.

I suppose that the lm() function does not recognize Varname as Variable1.

推荐答案

您可以使用lapply遍历变量.

fit <- lapply(Data[,c(...)], function(x) lm(x ~ Age + Speed + Gender + Mass, data = Data))

这会为您提供结果列表.

This gives you a list of your results.

c(...)应包含变量名作为字符串.另外,您可以根据变量在Data中的位置选择变量,例如Data[,1:5].

The c(...) should contain your variable names as strings. Alternatively, you can choose the variables by their position in Data, like Data[,1:5].

这篇关于在R中循环多个“多重线性回归"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆