轻松对不同的数据集执行相同的回归 [英] Easily performing the same regression on different datasets

查看:124
本文介绍了轻松对不同的数据集执行相同的回归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在几个不同的数据集(相同的因变量和独立变量)上执行相同的回归.但是,有许多自变量,我经常想测试添加/删除不同的变量.我想避免对所有不同的代码行进行所有这些更改,只是因为它们使用了不同的数据集.我是否可以只复制用于创建某些对象的公式,然后使用其他数据集创建一个新对象?例如,类似:

I'm performing the same regression on several different datasets (same dependent and independe variables). However, there are many independent variables, and I often want to test adding/removing different variables. I'd like to avoid making all these changes to different lines of code, just because they use different datasets. Can I instead just copy the formula that was used to create some object, and then create a new object using a different dataset? For example, something like:

fit1 <- lm(y ~ x1 + x2 + x3 + ..., data = dataset1)
fit2 <- lm(fit1$call, data = dataset2) # this doesn't work
fit3 <- lm(fit1$call, data = dataset3) # this doesn't work

这样,如果我想更新大量回归,我只需更新第一个回归,然后重新运行它们即可.

This way, if I want to update numerous regressions, I just update the first one and then rerun them all.

可以做到吗?最好不要使用循环或paste().

Can this be done? Preferably without using a loop or paste().

谢谢!

推荐答案

或使用update

(fit <- lm(mpg ~ wt, data = mtcars))

# Call:
#   lm(formula = mpg ~ wt, data = mtcars)
# 
# Coefficients:
#   (Intercept)           wt  
#        37.285       -5.344 

update(fit, data = mtcars[mtcars$hp < 100, ])

# Call:
#   lm(formula = mpg ~ wt, data = mtcars[mtcars$hp < 100, ])
# 
# Coefficients:
#   (Intercept)           wt  
#        39.295       -5.379 

update(fit, data = mtcars[1:10, ])

# Call:
#   lm(formula = mpg ~ wt, data = mtcars[1:10, ])
# 
# Coefficients:
#   (Intercept)           wt  
#        33.774       -4.285  

这篇关于轻松对不同的数据集执行相同的回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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