Loop linear regression and saving coefficients

放肆的年华 提交于 2019-11-28 00:31:01

There are several ways to do this. First, we create some generated data for illustration purposes:

set.seed(123)
dat <- expand.grid(year=2000:2010, AgeR=seq(-1,1,0.1))
dat$value <- rnorm(nrow(dat))

We can start with base-R. We split our data by year, fit the model and extract our coefficient. Then we bind everything together.

res <- do.call(rbind,lapply(split(dat, dat$year),function(x){
  fit <- lm(value~exp(AgeR), data=x)
  res <- data.frame(year=unique(x$year),coeff=coef(fit)[2])
  res
}))

We can do the same using data.table:

library(data.table)


res2 <- setDT(dat)[,.(coeff=coef(lm(value~exp(AgeR)))[2]),year]
res2

The broom package can be pretty useful here too.

library(dplyr)
library(broom)

mtcars %>%
  group_by(gear) %>%
  do(tidy(lm(mpg ~ am + cyl, data = .)))

Package nlme offers a handy function for this:

library(nlme)
coef(lmList(value ~ exp(AgeR)| year, data=dat))[,2, drop = FALSE]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!