r - 如何通过向量化以及来自 dplyr 的 group_by 函数迭代列
问题描述
正如用 dplyr 拟合多个回归模型所解释的,我们可以使用broomtidy
包中的函数跨组运行回归。例如,下面列出了iris数据集的演示代码,但是如果我们打算同时循环多个列并使用不同的因变量(Sepal.Length、Sepal.Width、Petal.Length )运行回归,该怎么办? ) 连同这个group_by操作,我怎样才能将(s)apply函数集成到这种情况下并获得这些回归模型的结果(3 * 3 = 9)?
library(dplyr);library(broom)
res1=iris%>%
group_by(Species)%>%
do(res=lm(Sepal.Length~Petal.Width,data=.))
tidy(res1, res)%>%
filter(term!="(Intercept)")
解决方案
您可以使用lme4::lmList
和来做到这一点broom.mixed::tidy
。您也许可以将其调整为管道,但这应该可以帮助您入门。在这里,基本上执行与管道lmList
中相同的功能,但我更容易概念化如何使用. 祝你好运!!group_by
dplyr
lapply
library(lme4)
library(broom.mixed)
# Selecting DVs
dvs <- names(iris)[1:3]
# Making formula objects
formula_text <- paste0(dvs, "~ Petal.Width | Species")
formulas <- lapply(formula_text, formula)
# Running grouped analyses and looping through DVs
results <- lapply(formulas, function(x) {
res <- broom.mixed::tidy(lmList(x, iris))
res[res$terms != "(Intercept)",]
})
# Renaming and viewing results
names(results) <- formula_text
并且,查看结果:
results
$`Sepal.Length~ Petal.Width | Species`
# A tibble: 3 x 6
group terms estimate p.value std.error statistic
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 setosa Petal.Width 0.930 0.154 0.649 1.43
2 versicolor Petal.Width 1.43 0.0000629 0.346 4.12
3 virginica Petal.Width 0.651 0.00993 0.249 2.61
$`Sepal.Width~ Petal.Width | Species`
# A tibble: 3 x 6
group terms estimate p.value std.error statistic
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 setosa Petal.Width 0.837 0.0415 0.407 2.06
2 versicolor Petal.Width 1.05 0.00000306 0.217 4.86
3 virginica Petal.Width 0.631 0.0000855 0.156 4.04
$`Petal.Length~ Petal.Width | Species`
# A tibble: 3 x 6
group terms estimate p.value std.error statistic
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 setosa Petal.Width 0.546 2.67e- 1 0.490 1.12
2 versicolor Petal.Width 1.87 3.84e-11 0.261 7.16
3 virginica Petal.Width 0.647 7.55e- 4 0.188 3.44
推荐阅读
- java - 版本 9.4.34.v20201102 的 Jetty ServletTester 类
- c++ - 某些类型的右值和左值实例的 C++ 类型转换运算符的意外行为
- java - ConfigFileApplicationListener 已弃用,只能用作 EnvironmentPostProcessor
- python - 如何仅通过加入和离开使这些频道动态可见?
- java - Android 动态点播功能问题与 coreLibraryDesugaringEnabled
- html - 以角度访问表格元素的索引值
- ruby-on-rails - 使用 FriendlyID 获取 rails 测试以反映实际行为
- regex - Powershell 函数返回中间值
- sql - 在查询中创建要加入的浮动表
- python - 在plotly python中处理多个x轴的重叠