R - 运行 由长格式数据框中的 id 标识的 tibbles 的回归

R - Running a regression for tibbles identified by an id out of a dataframe in long format

我想遍历由 stockID 标识的 data_all_long in long format that has 个元组。 使用 unique() 我将所有不同的 ID 存储在数据框中 "uniqueIDs"。 "Numberofrows" 是包含上述时间序列元组的列表的长度。

理想情况下,tmp 变量应临时存储长列表中某个特定 ID 的所有数据,以计算某个特定 ID 的回归并将其存储到向量中。 总体结果应该是一个向量,其中包含不同 ID 的所有回归系数。

for(i in uniqueIDs){
  for(j in 1:numberofrows){
      tmp <- rbind(tmp,filter(data_all_long, stockId == i))
  }
  beta[,i] <- lm(mrf ~ stockreturn, data = tmp) 
}

这里有人有什么想法吗?

根据我对问题的理解,以下可能会解决。
诀窍是通过 IDsapply 匿名函数对每个结果数据帧 split 数据。此函数将拟合模型并提取系数。

sp <- split(data_all_long, data_all_long$ID)
beta <- sapply(sp, function(tmp){
  fit <- lm(mrf ~ stockreturn, data = tmp)
  coef(fit)
})