Easily performing the same regression on different datasets

点点圈 提交于 2019-12-24 04:44:30

问题


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.

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

Thanks!


回答1:


Or use 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  



回答2:


Collect your datasets into a list and then use lapply. E.g.:

dsets <- list(dataset1,dataset2,dataset3)
lapply(dsets, function(x) lm(y ~ x1 + x2, data=x) )



回答3:


Not sure entirely that this what you want but you can do this as follows:

formula <- y ~ x1 + x2 + x3 + ...
fit1 <- lm(formula, data = dataset1)
fit2 <- lm(formula, data = dataset2) 
fit3 <- lm(formula, data = dataset3) 


来源:https://stackoverflow.com/questions/23964993/easily-performing-the-same-regression-on-different-datasets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!