R 按年份循环lm

R 按年份循环lm,r,group-by,lm,R,Group By,Lm,我在R中有一个数据帧,如上图所示 Id ln_W Year Exp 1 2.5 2010 15 1 2.3 2011 16 2 2.1 2010 20 3 2.5 2012 17 3 2.5 2013 18 我想在数据集中每年对ln_W~Exp进行回归,并将结果摘要保存为列表格式 有人知道怎么做吗?在base R中,我们按年份分割,使用Lappy循环列表,使用lm创建模型,并将输出存储为列表 数据 在BaseR中,我们按年份划

我在R中有一个数据帧,如上图所示

Id  ln_W  Year  Exp 
1   2.5   2010   15
1   2.3   2011   16
2   2.1   2010   20
3   2.5   2012   17
3   2.5   2013   18
我想在数据集中每年对ln_W~Exp进行回归,并将结果摘要保存为列表格式

有人知道怎么做吗?

在base R中,我们按年份分割,使用Lappy循环列表,使用lm创建模型,并将输出存储为列表

数据 在BaseR中,我们按年份划分,使用Lappy循环列表,使用lm创建模型,并将输出存储为列表

数据 您可以按年份分组,然后将lm摘要另存为列表列:

图书馆管理员 df%>% 分组单位按年份%>% SummarseFit=listlmln\u W~Exp,data=cur\u data%>%summary 输出:

一个tibble:4x2 年关 1 2010 2 2011 3 2012 4 2013 通过向链中添加%>%pullfit,仅获取摘要列表。 请注意,对于所提供的数据,这些摘要不会显示太多内容,只显示截距,因为没有足够的观测值进行拟合。

您可以按年份分组,然后将lm摘要另存为列表列:

图书馆管理员 df%>% 分组单位按年份%>% SummarseFit=listlmln\u W~Exp,data=cur\u data%>%summary 输出:

一个tibble:4x2 年关 1 2010 2 2011 3 2012 4 2013 通过向链中添加%>%pullfit,仅获取摘要列表。 请注意,对于所提供的数据,这些摘要不会显示太多内容,只显示截距,因为没有足够的观测值进行拟合。

为什么不使用by

数据:

为什么不用

数据:

out <- lapply(split(df1, df1$Year), function(x)
                   lm(ln_W ~ Exp, data = x))
library(lme4)
lmList(ln_W  ~Exp | Year, data = df1)
#Call: lmList(formula = ln_W ~ Exp | Year, data = df1) 
#Coefficients:
#     (Intercept)   Exp
#2010         3.7 -0.08
#2011         2.3    NA
#2012         2.5    NA
#2013         2.5    NA

#Degrees of freedom: 5 total; -3 residual
#Residual standard error: 0
df1 <- structure(list(Id = c(1L, 1L, 2L, 3L, 3L), ln_W = c(2.5, 2.3, 
2.1, 2.5, 2.5), Year = c(2010L, 2011L, 2010L, 2012L, 2013L), 
    Exp = c(15L, 16L, 20L, 17L, 18L)), class = "data.frame",
    row.names = c(NA, 
-5L))
res <- lapply(by(d, d$Year, lm, formula=ln_W ~ Exp), summary)
res
# $`2010`
# 
# Call:
# FUN(formula = ..1, data = data[x, , drop = FALSE])
# 
# Residuals:
#   ALL 2 residuals are 0: no residual degrees of freedom!
#   
#   Coefficients:
#   Estimate Std. Error t value Pr(>|t|)
# (Intercept)     3.70         NA      NA       NA
# Exp            -0.08         NA      NA       NA
# 
# Residual standard error: NaN on 0 degrees of freedom
# Multiple R-squared:      1,   Adjusted R-squared:    NaN 
# F-statistic:   NaN on 1 and 0 DF,  p-value: NA
# 
# 
# $`2011`
# 
# Call:
# FUN(formula = ..1, data = data[x, , drop = FALSE])
# 
# Residuals:
#   ALL 1 residuals are 0: no residual degrees of freedom!
#   
#   Coefficients: (1 not defined because of singularities)
# Estimate Std. Error t value Pr(>|t|)
# (Intercept)      2.3         NA      NA       NA
# Exp               NA         NA      NA       NA
# 
# Residual standard error: NaN on 0 degrees of freedom
# [...]
d <- structure(list(Id = c(1L, 1L, 2L, 3L, 3L), ln_W = c(2.5, 2.3, 
2.1, 2.5, 2.5), Year = c(2010L, 2011L, 2010L, 2012L, 2013L), 
    Exp = c(15L, 16L, 20L, 17L, 18L)), class = "data.frame", row.names = c(NA, 
-5L))