我想使用lm()函数在R中进行线性回归.我的数据是一年一度的时间序列,一年(22年),另一个州(50个州).我想为每个状态拟合一个回归,以便最后我有一个lm响应的向量.我可以想象为每个状态做循环然后在循环内进行回归并将每个回归的结果添加到向量.但是,这似乎不像R一样.在SAS中我会做一个'by'语句,在SQL中我会做'group by'.R的做法是什么?
我需要将 lm fit 对象存储在数据框中以进行进一步处理(这是必需的,因为我将在数据框中存储大约 200 多个回归)。我无法将 fit 对象存储在数据框中。以下代码产生错误消息:
x = runif(100)
y = 2*x+runif(100)
fit = lm(y ~x)
df = data.frame()
df = rbind(df, c(id="xx1", fitObj=fit))
Error in rbind(deparse.level, ...) :
invalid list argument: all variables should have the same length
Run Code Online (Sandbox Code Playgroud)
我想获取 dplyr 的“do”调用返回的数据框,示例如下:
> tacrSECOutput
Source: local data frame [24 x 5]
Groups: <by row>
sector control id1 fit count
1 Chemicals and Chemical Products S tSector <S3:lm> 2515
2 Construation and Real Estate S tSector <S3:lm> 985
Run Code Online (Sandbox Code Playgroud)
请注意,这只是一个示例输出。我想以上述格式创建数据框(适合 …