应用旨在将 data.frames 作为 R 中分组的 tibble 输入的函数的 tidyverse 方法是什么?

What is the tidyverse way to apply a function designed to take data.frames as input across a grouped tibble in R?

我编写了一个函数,该函数将多列作为输入,我想将其应用于分组的 tibble,我认为 purrr::map 可能是正确的方法,但我不'了解各种 map 函数的适当输入是什么。这是一个虚拟示例:

 myFun <- function(DF){
  DF %>% mutate(MyOut = (A * B)) %>% pull(MyOut) %>% sum()
}

MyDF <- data.frame(A = 1:5, B = 6:10)
myFun(MyDF)

这很好用。但是如果我想添加一些分组呢?

MyDF <- data.frame(A = 1:100, B = 1:100, Fruit = rep(c("Apple", "Mango"), each = 50))
MyDF %>% group_by(Fruit) %>% summarize(MyVal = myFun(.))

这行不通。我的 data.frame 或 tibble 中的每个组都获得相同的值。然后我尝试使用 purrr:

MyDF %>% group_by(Fruit) %>% map(.f = myFun)

显然,这需要字符数据作为输入,所以不是这样。

下一个变体基本上是我需要的,但输出是一个列表列表,而不是每个 Fruit 值一行的小标题:

MyDF %>% group_by(Fruit) %>% group_map(~ myFun(.))

我们可以在group_modify

中使用OP的功能
library(dplyr)
MyDF %>% 
   group_by(Fruit) %>% 
   group_modify(~ .x %>% 
       summarise(MyVal = myFun(.x))) %>%
   ungroup

-输出

# A tibble: 2 × 2
  Fruit  MyVal
  <chr>  <int>
1 Apple  42925
2 Mango 295425

或者在 group_map.y 是分组列

MyDF %>% 
   group_by(Fruit) %>%
   group_map(~ bind_cols(.y, MyVal = myFun(.))) %>%
   bind_rows
# A tibble: 2 × 2
  Fruit  MyVal
  <chr>  <int>
1 Apple  42925
2 Mango 295425