遍历回归模型项的组合 [英] Looping over combinations of regression model terms

查看:92
本文介绍了遍历回归模型项的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以

reg=lm(y ~ x1+x2+x3+z1,data=mydata)

在最后一项z1的地方,我想遍历一组不同的变量,从z1z10,对每个变量进行回归分析,以最后一项作为变量.例如.在第二次运行中,我想使用

In the place of the last term, z1, I want to loop through a set of different variables, z1 through z10, running a regression for each with it as the last term. E.g. in second run I want to use

reg=lm(y ~ x1+x2+x3+z2,data=mydata)

在第三轮中:

reg=lm(y ~ x1+x2+x3+z3,data=mydata)

如何通过遍历z变量列表来实现此目的自动化?

How can I automate this by looping through the list of z-variables?

推荐答案

使用此虚拟数据:

dat1 <- data.frame(y = rpois(100,5),
x1 = runif(100),
x2 = runif(100),
x3 = runif(100),
z1 = runif(100),
z2 = runif(100)
)

您可以通过以下方式获得两个lm对象的列表:

You could get your list of two lm objects this way:

 lapply(dat1[5:6], function(x) lm(dat1$y ~ dat1$x1 + dat1$x2 + dat1$x3 + x))

遍历这两列并将其作为参数替换为lm调用.

Which iterates through those two columns and substitutes them as arguments into the lm call.

就像亚历克斯(Alex)在下面指出的那样,最好将名称通过公式传递,而不是像我在此处所做的实际数据列那样传递.

As Alex notes below, it's preferable to pass the names through the formula, rather than the actual data columns as I have done here.

这篇关于遍历回归模型项的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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