当使用 lapply 时,从 lm 中提取残差值和日期
Extracting Residuals values and Date from lm, when lapply is used
我有一个包含 507 列的数据框。第 1 列是观察日期。第 2 列到第 504 列是我的因变量。 505、506 和 507 列是自变量。我写了一个函数来对每个因变量进行单独的回归:
varlist<-names(df)[2:504]
models <- lapply(varlist, function(x) {
lm( na.action = na.exclude,
substitute(i ~ rmrf + smb + hml,
list(i = as.name(x))
),
data = df)
})
如何将所有残差结果导出到一个单独的数据框中,连同它来自哪个因变量的相应标题以及它来自什么日期?
我可以使用此方法从单个模型访问残差:
resid(models[[1]])
但我无法确定这适用于哪个因变量以及残差对应的日期(观察)。另外,我还没有找到从所有 503 模型中导出残差的方法。
Resid(models[[1:503]])
给我以下错误:
模型错误[[1:503]]:递归索引在级别 3 失败
# All the dep var
x = df[,505:507]
# All the indep var
y = df[,2:504]
# Fit all the models, use a little bit of scoping abuse
list_models = lapply(y, function(y) with(x, lm(y~rmf + smb + htl)))
# Get resid for all models
list_resid = lapply(list_models, resid)
# If you want them in a data.frame instead of list
df_resid = do.call(cbind.data.frame, list_resid)
# Add the dates
df_resid = cbind(date = df[,1], df_resid)
# Reproducible example, just generating some fake data in the same structure as your data
df = matrix(runif(50*507), nrow = 50, ncol = 507)
df = data.frame(df)
df[,1] = seq(as.Date("2017/1/1"), as.Date("2017/2/19"), "days")
names(df) = paste0("var", 1:507)
names(df)[505:507] = c("rmf", "smb", "htl")
names(df)[1] = "Date"
我有一个包含 507 列的数据框。第 1 列是观察日期。第 2 列到第 504 列是我的因变量。 505、506 和 507 列是自变量。我写了一个函数来对每个因变量进行单独的回归:
varlist<-names(df)[2:504]
models <- lapply(varlist, function(x) {
lm( na.action = na.exclude,
substitute(i ~ rmrf + smb + hml,
list(i = as.name(x))
),
data = df)
})
如何将所有残差结果导出到一个单独的数据框中,连同它来自哪个因变量的相应标题以及它来自什么日期?
我可以使用此方法从单个模型访问残差:
resid(models[[1]])
但我无法确定这适用于哪个因变量以及残差对应的日期(观察)。另外,我还没有找到从所有 503 模型中导出残差的方法。
Resid(models[[1:503]])
给我以下错误:
模型错误[[1:503]]:递归索引在级别 3 失败
# All the dep var
x = df[,505:507]
# All the indep var
y = df[,2:504]
# Fit all the models, use a little bit of scoping abuse
list_models = lapply(y, function(y) with(x, lm(y~rmf + smb + htl)))
# Get resid for all models
list_resid = lapply(list_models, resid)
# If you want them in a data.frame instead of list
df_resid = do.call(cbind.data.frame, list_resid)
# Add the dates
df_resid = cbind(date = df[,1], df_resid)
# Reproducible example, just generating some fake data in the same structure as your data
df = matrix(runif(50*507), nrow = 50, ncol = 507)
df = data.frame(df)
df[,1] = seq(as.Date("2017/1/1"), as.Date("2017/2/19"), "days")
names(df) = paste0("var", 1:507)
names(df)[505:507] = c("rmf", "smb", "htl")
names(df)[1] = "Date"