[英]Iteratively adding variables to an lm() function in R?
Simple question, but I'm finding myself boggled.简单的问题,但我发现自己很困惑。
I'm looking to make a loop that will continuously add variables to the IV of an lm() function.我正在寻找一个循环,它将不断地将变量添加到 lm() function 的 IV 中。 I would test the results of the LM until a condition is met.
我会测试 LM 的结果,直到满足条件。 I'm just having trouble finding a way to dynamically adding variables to the IV part of the regression, one at a time.
我只是很难找到一种方法来动态地将变量添加到回归的 IV 部分,一次一个。
The 1st iteration would look like:第一次迭代看起来像:
lm(Y ~ X, data = data)
The second iteration like:第二次迭代如:
lm(Y ~ X + X2, data = data)
The third iteration like:第三次迭代如:
lm(Y ~ X + X2 + X3, data = data)
And so on...等等...
If any of you could point me in the right direction, I'd appreciate it very much.如果你们中的任何人能指出我正确的方向,我将非常感激。
Thanks!谢谢!
An alternative way is to use Y ~.
另一种方法是使用
Y ~.
as the formula and provide the subset of data as required.作为公式并根据需要提供数据子集。 Here,
.
在这里,
.
means "all columns not otherwise in the formula" (see ?formula
).表示“公式中没有的所有列”(参见
?formula
)。 Using mtcars
as an example:以
mtcars
为例:
Y <- 'mpg'
Xs <- names(mtcars)[-1]
fits <- lapply(seq_along(Xs), function(x){
lm(paste(Y, '~ .'), data = mtcars[, c(Y, Xs[1:x])])
})
We can use reformulate
to create the formula after passing the independent variables as a list
在将自变量作为
list
传递后,我们可以使用reformulate
公式来创建公式
out <- lapply(list("X", c("X, "X2"), c("X", "X2", "X3")),
function(x) lm(reformulate(x, response = "Y"), data = data))
Or make it automated或者让它自动化
Xs <- setdiff(names(data), "Y")
ind <- sequence(seq_along(Xs))
lapply(split(Xs[ind], cumsum(ind == 1)), function(x)
lm(reformulate(x, response = "Y"), data = data))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.