[英]Keep other columns when doing group_by + summarise with dplyr
I want to do a group_by + summarise
operation on only two columns with one group attribute while keeping the other three columns unchanged which have the same number for every row.我想只对具有一个组属性的两列执行
group_by + summarise
操作,同时保持其他三列不变,每行具有相同的数字。 How can I do that?我怎样才能做到这一点? eg
例如
> data<- data.frame(a=1:10, b=rep(1,10), c=rep(2,10), d=rep(3,10), e= c("small", "med", "larg", "larg", "larg", "med", "small", "small", "small", "med"))
> data %>% group_by(e) %>% summarise(a=mean(a))
# A tibble: 3 × 2
e a
<chr> <dbl>
1 larg 4
2 med 6
3 small 6.25
but I want但我想要
# A tibble: 3 × 5
e a b c d
<chr> <dbl> <dbl> <dbl> <dbl>
1 larg 4 1 2 3
2 med 6 1 2 3
3 small 6.25 1 2 3
group_by + summarise
always drops other columns. group_by + summarise
总是删除其他列。 How can I do that?我怎样才能做到这一点?
Add the other columns to group_by
:将其他列添加到
group_by
:
> library(tidyverse)
> data <- data.frame(a=1:10, b=rep(1,10), c=rep(2,10), d=rep(3,10), e= c("small", "med", "larg", "larg", "larg", "med", "small", "small", "small", "med"))
> data %>% group_by(e, b, c, d) %>% summarise(a=mean(a))
`summarise()` has grouped output by 'e', 'b', 'c'. You can override using the `.groups` argument.
# A tibble: 3 x 5
# Groups: e, b, c [3]
e b c d a
<chr> <dbl> <dbl> <dbl> <dbl>
1 larg 1 2 3 4
2 med 1 2 3 6
3 small 1 2 3 6.25
And you can always calculate a new variable with group + summarise
and keep the rest of your dataframe "intact" adding across()
in the summarise.并且您始终可以使用
group + summarise
计算一个新变量,并保持数据框的其余部分“完整”在汇总中添加 cross across()
。 This could be useful if your other variables arent going to be the same always.如果您的其他变量并不总是相同,这可能很有用。
data %>% group_by(e) %>%
summarise(a=mean(a), across())
# A tibble: 10 x 5
# Groups: e [3]
e a b c d
<chr> <dbl> <dbl> <dbl> <dbl>
1 larg 4 1 2 3
2 larg 4 1 2 3
3 larg 4 1 2 3
4 med 6 1 2 3
5 med 6 1 2 3
6 med 6 1 2 3
7 small 6.25 1 2 3
8 small 6.25 1 2 3
9 small 6.25 1 2 3
10 small 6.25 1 2 3
It is unclear how many columns you want to treat as grouping variable.目前尚不清楚您要将多少列视为分组变量。 If the number is small, @tauft's answer is sufficient.
如果数量很少,@tauft 的回答就足够了。 Otherwise, we can use
across
with group_by
so that we can use <tidy-select>
to select the columns to group.否则,我们可以使用
across
和group_by
以便我们可以使用<tidy-select>
来选择要分组的列。
library(dplyr)
data2 <- data %>%
group_by(across(-a)) %>%
summarise(a = mean(a), .groups = "drop") %>%
relocate(e, a, .before = b)
data2
# # A tibble: 3 x 5
# e a b c d
# <chr> <dbl> <dbl> <dbl> <dbl>
# 1 larg 4 1 2 3
# 2 med 6 1 2 3
# 3 small 6.25 1 2 3
The above can also written as follows.上面也可以写成如下。
data2 <- data %>%
group_by(across(b:e)) %>%
summarise(a = mean(a), .groups = "drop") %>%
relocate(e, a, .before = b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.