Reputation: 23898
I want to perform ANOVA for each level of a factor. I can do this with dplyr::do
but would like to have with purrr
also. Any hint, please.
library(tidyverse)
df1 <- mtcars
df1$cyl <- factor(df1$cyl)
df1$gear <- factor(df1$gear)
fm1 <-
df1 %>%
dplyr::group_by(gear) %>%
dplyr::do(m1 = summary(aov(mpg ~ cyl, data = .)))
fm1$m1
> fm1$m1
[[1]]
Df Sum Sq Mean Sq F value Pr(>F)
cyl 2 69.03 34.52 4.596 0.033 *
Residuals 12 90.11 7.51
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
[[2]]
Df Sum Sq Mean Sq F value Pr(>F)
cyl 1 137.3 137.3 8.123 0.0172 *
Residuals 10 169.0 16.9
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
[[3]]
Df Sum Sq Mean Sq F value Pr(>F)
cyl 2 167.4 83.68 16.74 0.0564 .
Residuals 2 10.0 5.00
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
fm2 <-
df1 %>%
dplyr::group_by(gear) %>%
tidyr::nest() %>%
dplyr::mutate(m2 = purrr::map(.x = data, .f = ~ summary(aov(mpg ~ cyl, data = .)))) %>%
tidyr::unnest()
Upvotes: 1
Views: 4753
Reputation: 4879
You can use a nested dataframe and then save all summaries in a new list column:
library(tidyverse)
df1 <- mtcars
df_aov <- df1 %>%
dplyr::group_by(gear) %>%
tidyr::nest() %>%
dplyr::mutate(.data = .,
aov_results = data %>% purrr::map(.x = ., .f = ~ summary(aov(mpg ~ cyl, data = .))))
df_aov$aov_results[[1]]
#> Df Sum Sq Mean Sq F value Pr(>F)
#> cyl 1 137.3 137.3 8.123 0.0172 *
#> Residuals 10 169.0 16.9
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Created on 2018-10-02 by the reprex package (v0.2.1)
Upvotes: 3