将整个分组的数据框传递到一个函数总结

发布于 2025-02-13 10:08:36 字数 954 浏览 1 评论 0原文

使用新的总结 dplyr 1.0.0可以传递一个函数以汇总比返回tibble,

library(tidyverse)

df <- tibble(
  grp = rep(1:2, each = 5), 
  x = c(rnorm(5, -0.25, 1), rnorm(5, 0, 1.5)),
  y = c(rnorm(5, 0.25, 1), rnorm(5, 0, 0.5)),
)

quibble <- function(x, q = c(0.25, 0.5, 0.75)) {
  tibble(x = quantile(x, q), q = q)
}

df %>% 
  group_by(grp) %>% 
  summarise(quibble(x, c(0.25, 0.5, 0.75)))

我想知道是否可以将功能传递到incoper总结整个分组的数据框架,而不是列的名称。 例如

df %>% 
  group_by(grp) %>% 
  summarise(my_function(d))

d是第一个df for grp == 1,然后df for grp ================================= 2

我认为我知道如何使用purrr :: Map进行操作,

df %>% 
  group_by(grp) %>% 
  nest() %>% 
  mutate(temp = map(data, my_function)) %>% 
  unnest(temp)

但是我想知道是否可以使用总结进行操作。

With the new summarise from dplyr 1.0.0 it is possible to pass a function to summarise than returns a tibble

library(tidyverse)

df <- tibble(
  grp = rep(1:2, each = 5), 
  x = c(rnorm(5, -0.25, 1), rnorm(5, 0, 1.5)),
  y = c(rnorm(5, 0.25, 1), rnorm(5, 0, 0.5)),
)

quibble <- function(x, q = c(0.25, 0.5, 0.75)) {
  tibble(x = quantile(x, q), q = q)
}

df %>% 
  group_by(grp) %>% 
  summarise(quibble(x, c(0.25, 0.5, 0.75)))

I wonder whether it is possible to pass to the function inside summarise the whole grouped data frame instead of the names of the columns.
Something like

df %>% 
  group_by(grp) %>% 
  summarise(my_function(d))

where d is first df for grp == 1 and then df for grp == 2.

I think that I know how to do it with purrr::map

df %>% 
  group_by(grp) %>% 
  nest() %>% 
  mutate(temp = map(data, my_function)) %>% 
  unnest(temp)

but I wonder whether it is possible to do it with summarise.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

要走干脆点 2025-02-20 10:08:36
tibble(gr=c(1,1,2), a=c(1,2,10), b=c(1,2,10)) %>% 
    print() %>% 
# A tibble: 3 x 3
#      gr     a     b
#   <dbl> <dbl> <dbl>
# 1     1     1     1
# 2     1     2     2
# 3     2    10    10
    group_by(gr) %>% 
    summarise(r=sum(cur_data()))
# A tibble: 2 x 2
#      gr     r
#   <dbl> <dbl>
# 1     1     6
# 2     2    20
tibble(gr=c(1,1,2), a=c(1,2,10), b=c(1,2,10)) %>% 
    print() %>% 
# A tibble: 3 x 3
#      gr     a     b
#   <dbl> <dbl> <dbl>
# 1     1     1     1
# 2     1     2     2
# 3     2    10    10
    group_by(gr) %>% 
    summarise(r=sum(cur_data()))
# A tibble: 2 x 2
#      gr     r
#   <dbl> <dbl>
# 1     1     6
# 2     2    20
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文