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

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

问题描述

我正在以这种形式运行回归

I'm running a regression in the form

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.

正如亚历克斯在下面指出的,最好通过公式传递名称,而不是像我在这里所做的那样传递实际数据列.

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天全站免登陆