I have a fairly simple question with an already convoluted answer (via loop), but I'm hoping someone can point me to a more elegant answer in purrr
.
Basically, I'm thinking of an introduction to permutations for my students as a computational alternative to your boilerplate means to statistical inference (i.e. t and z values). In the toy example I have set up, I'm doing some grouped means (via dplyr'
's group_by()
and summarize()
) along with permutations via modelr
. I'd like to know how I can store the grouped means in the nested tibble containing the permutations.
I already have a solution via loop (that bypasses storing them in the tibble with the permutations), but I'd like to see what the solution in purrr
would be.
Here's a basic example of what I'm doing.
library(tidyverse)
library(modelr)
mtcars %>%
permute(1000, mpg) -> perm_mtcars
perm_sums <- tibble()
# convoluted loop answer, does what I want,
# but is convoluted loop and spams the R console with messages
# about "ungrouping output" because of group_by()
for (i in 1:1000) {
perm_mtcars %>%
slice(i) %>%
pull(perm) %>% as.data.frame %>%
group_by(cyl) %>%
summarize(mean = mean(mpg)) %>%
mutate(perm = i) -> hold_this
perm_sums <- bind_rows(perm_sums, hold_this)
}
# what I'd like to do, based off how easy this is to pull off with running regressions,
# tidying the output, and extracting that.
perm_mtcars %>%
mutate(groupsums = map(perm, ~summarize(???)) %>%
# and where I might be getting ahead of myself
pull(groupsums) %>%
map2_df(., seq(1, 1000), ~mutate(.x, perm = .y))
This is probably easy in purrr
but purrr
is mostly Greek to me right now, to borrow that expression.