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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…