![](/img/trans.png)
[英]How i can calculate the correlation of each variable within the same grouping variable using dplyr?
[英]can I switch the grouping variable in a single dplyr statement?
这是一个简单的例子来说明这个问题:
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
执行相同的dplyr
我失败了,因为第一个group_by
是持久性的,并且分组是由b
和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
解决方案?
试试这个:
> 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使用的新版本%>%
而非%.%
并ungroup
不再需要(根据大卫Arenburg的评论)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.