我想用dplyr为每个小时(因子变量)拟合一个模型,我得到了一个错误,我不太确定是什么问题。
df.h <- data.frame(
hour = factor(rep(1:24, each = 21)),
price = runif(504, min = -10, max = 125),
wind = runif(504, min = 0, max = 2500),
temp = runif(504, min = - 10, max = 25)
)
df.h <- tbl_df(df.h)
df.h <- group_by(df.h, hour)
group_size(df.h) # checks out, 21 obs. for each factor variable
# different attempts:
reg.models <- do(df.h, formula = price ~ wind + temp)
reg.models <- do(df.h, .f = lm(price ~ wind + temp, data = df.h))
我试过各种不同的方法,但就是不管用。
8条答案
按热度按时间4dc9hkyq1#
在2015年5月左右,最简单的方法是使用
broom
。broom
包含三个函数,用于按组处理来自统计操作的复杂返回对象:tidy
(处理来自按组统计操作的系数向量)、glance
(处理来自按组统计操作的汇总统计)和augment
(处理来自按组统计操作的观察水平结果)。下面演示了如何使用它将线性回归的各种结果按组提取到整齐的
data_frame
s中。1.
tidy
:其给出,
1.
augment
:其给出,
1.
glance
:其给出,
63lcw9qa2#
截至2020年中期(并更新为适应
dplyr
1.0+截至2022-04),tchakravarty's answer将失败。为了避免broom
和dpylr
似乎相互作用的新方法,可以使用以下broom::tidy
、broom::augment
和broom::glance
的组合。我们只需要将它们与nest_by()
和summarize()
结合使用(以前在do()
和后来的unnest()
中)。感谢Bob Muenchen's Blog的启发。
5hcedyr03#
在dplyr 0.4中,您可以执行以下操作:
kqlmhetl4#
do
的文档:.f
:应用于每个片段的函数。提供给.f的第一个未命名参数将是一个 Dataframe 。所以:
可能还有助于保存模型适合的时间:
qlfbtfca5#
我相信有一个比loki's answer更简洁的答案,它放弃了自替换的/superseded
do()
:与他们回答类似,为了访问,只需将所需的任何组件解嵌套即可:
dfty9e196#
我认为你可以用更合适的方式使用
dplyr
,你不需要像@fabians anwser那样定义函数。或
**编辑:**当然,没有
failwith
也可以工作fcwjkofz7#
tidyverse后期的几个修订版,
do()
运算符被取代,我们可以用少一行代码来适应每组一个模型。由reprex package(v2.0.1)于2022-04-20创建
hjqgdpho8#
从dplyr 1.0.0开始,
group_split
为这个操作提供了一个方便的快捷方式:创建于2023-05-15带有reprex v2.0.2