我可以在单个dplyr语句中切换分组变量吗? [英] can I switch the grouping variable in a single dplyr statement?

查看:86
本文介绍了我可以在单个dplyr语句中切换分组变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个简单的例子来说明问题:

Here's a simple example to illustrate the issue:

library(data.table)
dt = data.table(a = c(1,1,2,2), b = 1:2)

dt[, c := cumsum(a), by = b][, d := cumsum(a), by = c]
#   a b c d
#1: 1 1 1 1
#2: 1 2 1 2
#3: 2 1 3 2
#4: 2 2 3 4

尝试在 dplyr中执行相同操作我失败,因为第一个 group_by 是持久的,分组由 b code> c

Attempting to do the same in dplyr I fail because the first group_by is persistent and the grouping is by both b and c:

df = data.frame(a = c(1,1,2,2), b = 1:2)

df %.% group_by(b) %.% mutate(c = cumsum(a)) %.%
       group_by(c) %.% mutate(d = cumsum(a))
#  a b c d
#1 1 1 1 1
#2 1 2 1 1
#3 2 1 3 2
#4 2 2 3 2

这是错误还是功能?如果它是一个特性,那么如何在一个语句中复制 data.table 解决方案?

Is this a bug or a feature? If it's a feature, then how would one replicate the data.table solution in a single statement?

推荐答案

尝试:

> df %>% group_by(b) %>% mutate(c = cumsum(a)) %>%
+        group_by(c) %>% mutate(d = cumsum(a))
Source: local data frame [4 x 4]
Groups: c

  a b c d
1 1 1 1 1
2 1 2 1 2
3 2 1 3 2
4 2 2 3 4

更新

使用较新版本的dplyr使用%>%,而不是%。 / code>和 ungroup 不再需要(按照David Arenburg的评论)。

With newer version of dplyr use %>% rather than %.% and ungroup is no longer needed (as per David Arenburg's comment).

这篇关于我可以在单个dplyr语句中切换分组变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆