我正在try 为从数据集的子集生成的多个不同的线性回归模型生成截距和系数的数据帧.很遗憾,我不能分享我的数据,但我可以用mtars集来解释.我正在创建一个回归模型,根据carb的每个值从cyl、hp和wt预测mpg. 在挖掘了一段时间后,我发现了许多示例,它们都能做我想要的事情,但仅适用于具有1个预测器(如mpg~wt)的模型.当我加上其他术语时,一切都分崩离析了.这就是到目前为止我的工作所基于的: https://community.rstudio.com/t/extract-slopes-by-group-broom-dplyr/2751/8个 Efficient way to extract coefficients from many linear regression lines
这就是我试过的
library(tidyverse);library(broom)
df <- mtcars
tryme <- df %>%
split(.$carb)%>%
map(~lm(mpg~cyl+hp+wt,data=.x)) %>%
map_df(tidy)
结果是这样的
term estimate std.error statistic p.value
1 (Intercept) 46.034633 7.68430306 5.99073626 9.31E-03
2 cyl 2.650503624 4.14371413 0.63964442 5.68E-01
3 hp -0.230007961 0.1573354 -1.46189576 2.40E-01
4 wt -5.231999683 9.23136027 -0.56676368 6.11E-01
5 (Intercept) 39.84451509 2.95537984 13.48202845 1.03E-05
6 cyl -0.846094229 0.93995084 -0.90014732 4.03E-01
7 hp -0.007452737 0.03998485 -0.18638901 8.58E-01
8 wt -4.133340298 1.42757472 -2.89535829 2.75E-02
9 (Intercept) 17.50267062 22.13706712 0.79064993 5.74E-01
10 cyl NA NA NA NA
11 hp NA NA NA NA
12 wt -0.3115727 5.73067255 -0.05436931 9.65E-01
13 (Intercept) 45.33390978 12.93999647 3.50339429 1.28E-02
14 cyl -4.195214198 3.492613 -1.20116778 2.75E-01
15 hp 0.029361878 0.04927895 0.59583008 5.73E-01
16 wt -1.239041102 1.03937377 -1.19210349 2.78E-01
17 (Intercept) 19.7 NaN NaN NaN
18 cyl NA NA NA NA
19 hp NA NA NA NA
20 wt NA NA NA NA
21 (Intercept) 15 NaN NaN NaN
22 cyl NA NA NA NA
23 hp NA NA NA NA
24 wt NA NA NA NA
我想要的是一张看起来像这样的桌子:
carb intercept cyl hp wt
1 46.034633 2.650503624 -0.230007961 -5.231999683
2 39.84451509 -0.846094229 -0.007452737 -4.133340298
3 17.50267062 NA NA -0.3115727
4 45.33390978 -4.195214198 0.029361878 -1.239041102
6 19.7 NA NA NA
8 15 NA NA NA
我不知道如何引入分组变量的值.如果我能将其添加到我已有的数据中,我知道如何将数据转置为我需要的形式.
我正在更新一点,因为这里的一个答案给了我想要的东西,但导致了一个我似乎无法修复的错误.该解决方案使用nlme库中的lmList.我使用的代码是这样的
fit <- lmList(SentLength~Unified_UPPER+Unified_LOWER+GRADE | SentType, data=df, na.omit)
and this is the data I am running it on:
SentType SentLength Unified_UPPER Unified_LOWER GRADE
Jail 0.06578947 0.06666667 0.06666667 3
Other 0 6 0 4
Other 0 6 6 1
Probation 6 0 0 1
Other 0 9 0 6
Jail 1.41447368 6 0 3
Probation 6 0 0 1
Probation 6 0 0 1
Probation 12 0 0 2
Jail 6 16 6 6
Prison 36 27 21 5
Probation 24 9 0 6
Jail 0.23026316 0.5 0 1
Jail 0.09868421 0.06666667 0.06666667 1
Probation 60 27 21 6
Probation 6 1 0 1
Probation 24 0 0 3
Prison 36 54 36 8
Probation 24 9 0 6
Probation 6 0 0 1
Probation 0 0.06666667 0.06666667 1
Probation 24 0 0 3
Jail 0.13157895 1 0.06666667 1
Jail 0.09868421 1 0.1 1
Prison 42 60 48 8
Probation 6 0 0 2
Other 0 0 0 1
Prison 6 6 6 1
Prison 6 6 6 1
Other 0 16 9 7
我得到了这个错误: Na.ail.default(Data)中出错:对象中缺少值 尽管数据中没有遗漏任何值.有人能帮上忙吗?