我想使用lm()
函数在R中进行线性回归。我的数据是一个年度时间序列,其中一个字段代表年份(22年),另一个字段代表州(50个州)。我想要拟合每个状态的回归,以便在结束时我有一个lm响应的向量。我可以想象为每个状态执行for循环,然后在循环中进行回归,并将每个回归的结果添加到一个向量中。然而,这看起来不太像R-like。在SAS中,我会执行“by”语句,而在SQL中,我会执行“group by”。做这个的R方法是什么?
发布于 2009-07-23 04:55:41
以下是使用lme4
包的一种方法。
library(lme4)
d <- data.frame(state=rep(c('NY', 'CA'), c(10, 10)),
year=rep(1:10, 2),
response=c(rnorm(10), rnorm(10)))
xyplot(response ~ year, groups=state, data=d, type='l')
fits <- lmList(response ~ year | state, data=d)
fits
#------------
Call: lmList(formula = response ~ year | state, data = d)
Coefficients:
(Intercept) year
CA -1.34420990 0.17139963
NY 0.00196176 -0.01852429
Degrees of freedom: 20 total; 16 residual
Residual standard error: 0.8201316
发布于 2009-07-31 19:30:45
下面是一种使用plyr包的方法:
d <- data.frame(
state = rep(c('NY', 'CA'), 10),
year = rep(1:10, 2),
response= rnorm(20)
)
library(plyr)
# Break up d by state, then fit the specified model to each piece and
# return a list
models <- dlply(d, "state", function(df)
lm(response ~ year, data = df))
# Apply coef to each model and return a data frame
ldply(models, coef)
# Print the summary of each model
l_ply(models, summary, .print = TRUE)
发布于 2009-07-24 11:32:36
在我看来,对于这类数据,混合线性模型是更好的方法。下面的代码给出了固定效果的整体趋势。随机效应表明每个州的趋势与全球趋势有何不同。相关结构考虑了时间自相关。看看Pinheiro & Bates (S和S-Plus的混合效果模型)。
library(nlme)
lme(response ~ year, random = ~year|state, correlation = corAR1(~year))
https://stackoverflow.com/questions/1169539
复制相似问题