【发布时间】:2020-10-21 20:22:20
【问题描述】:
我有一个相当简单的问题,答案已经很复杂(通过循环),但我希望有人能在purrr 中指出一个更优雅的答案。
基本上,我正在考虑为我的学生介绍排列,作为统计推断的样板方法(即 t 和 z 值)的计算替代方法。在我设置的玩具示例中,我正在做一些分组方法(通过dplyr' 的group_by() 和summarize())以及通过modelr 的排列。我想知道如何将分组均值存储在包含排列的嵌套小标题中。
我已经有一个通过循环的解决方案(绕过将它们存储在带有排列的小标题中),但我想看看purrr 中的解决方案是什么。
这是我正在做的一个基本示例。
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))
这在purrr 中可能很容易,但purrr 现在对我来说主要是希腊语,借用那个表达方式。
【问题讨论】:
标签: r permutation purrr