MYa*_*208 2 statistics regression r
我想知道是否有办法为每个回归方程提取R2.
d <- data.frame(
state = rep(c('NY', 'CA'), 10),
year = rep(1:10, 2),
response= rnorm(20)
)
library(plyr)
models <- dlply(d, "state", function(df)
lm(response ~ year, data = df))
ldply(models, coef)
l_ply(models, summary, .print = TRUE)
Run Code Online (Sandbox Code Playgroud)
我试过了
l_ply(models, summary$r.squared, .print = TRUE)
Run Code Online (Sandbox Code Playgroud)
但是这会抛出以下错误消息
Error in summary$r.squared : object of type 'closure' is not subsettable
Run Code Online (Sandbox Code Playgroud)
您可以这样做以获得R平方值和系数:
ldply(models, function(x) {r.sq <- summary(x)$r.squared
intercept <- summary(x)$coefficients[1]
beta <- summary(x)$coefficients[2]
data.frame(r.sq, intercept, beta)})
# state r.sq intercept beta
#1 CA 0.230696121 0.4915617 -0.12343947
#2 NY 0.003506936 0.1971734 -0.01227367
Run Code Online (Sandbox Code Playgroud)
使用扫帚包将统计分析对象转换为data.frames并dplyr用于bind_rows:
library(dplyr) ; library(broom)
cbind(
state = attr(models, "split_labels"),
bind_rows(lapply(models, function(x) cbind(
intercept = tidy(x)$estimate[1],
beta = tidy(x)$estimate[2],
glance(x))))
)
state intercept beta r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC deviance df.residual
1 CA 0.38653551 -0.05459205 0.01427426 -0.10894146 1.434599 0.1158477 0.7423473 2 -16.68252 39.36505 40.27280 16.46460 8
2 NY 0.09028554 -0.08462742 0.04138985 -0.07843642 1.287909 0.3454155 0.5729312 2 -15.60387 37.20773 38.11549 13.26968 8
Run Code Online (Sandbox Code Playgroud)