簡體   English   中英

使用 dplyr 進行 group_by + 匯總時保留其他列

[英]Keep other columns when doing group_by + summarise with dplyr

我想只對具有一個組屬性的兩列執行group_by + summarise操作,同時保持其他三列不變,每行具有相同的數字。 我怎樣才能做到這一點? 例如

> 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

但我想要

# 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總是刪除其他列。 我怎樣才能做到這一點?

將其他列添加到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

並且您始終可以使用group + summarise計算一個新變量,並保持數據框的其余部分“完整”在匯總中添加 cross across() 如果您的其他變量並不總是相同,這可能很有用。

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

目前尚不清楚您要將多少列視為分組變量。 如果數量很少,@tauft 的回答就足夠了。 否則,我們可以使用acrossgroup_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

上面也可以寫成如下。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM