Skip to main content

dplyr::ungroup

dplyr::ungroup は、tidyverse コレクションの dplyr パッケージに含まれる関数で、データフレームのグループ化を解除するために使用される。

クイックリファレンス

library(tidyverse)

grouped_df %>%
ungroup()
penguins %>%
group_by(island) %>%
ungroup()

# # A tibble: 344 × 7
# species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex
# <fct> <fct> <dbl> <dbl> <int> <int> <fct>
# 1 Adelie Torgersen 39.1 18.7 181 3750 male
# 2 Adelie Torgersen 39.5 17.4 186 3800 female
# 3 Adelie Torgersen 40.3 18 195 3250 female
# 4 Adelie Torgersen NA NA NA NA NA
# 5 Adelie Torgersen 36.7 19.3 193 3450 female
# 6 Adelie Torgersen 39.3 20.6 190 3650 male
# 7 Adelie Torgersen 38.9 17.8 181 3625 female
# 8 Adelie Torgersen 39.2 19.6 195 4675 male
# 9 Adelie Torgersen 34.1 18.1 193 3475 NA
# 10 Adelie Torgersen 42 20.2 190 4250 NA
# # ℹ 334 more rows
# # ℹ Use `print(n = ...)` to see more rows

基本構文

ungroup(x, ...)
引数説明
xtibble。
...グループ化から削除する列名を指定。

使用例

1. グループ化の解除

penguins %>%
group_by(species) %>%
summarise(avg_body_mass = mean(body_mass_g, na.rm = TRUE)) %>%
ungroup()

# # A tibble: 3 × 2
# species avg_body_mass
# <fct> <dbl>
# 1 Adelie 3701.
# 2 Chinstrap 3733.
# 3 Gentoo 5076.

2. グループのレベルを下げる

penguins %>%
group_by(species, island) %>%
ungroup(island)

# # A tibble: 344 × 7
# # Groups: species [3]
# species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex
# <fct> <fct> <dbl> <dbl> <int> <int> <fct>
# 1 Adelie Torgersen 39.1 18.7 181 3750 male
# 2 Adelie Torgersen 39.5 17.4 186 3800 female
# 3 Adelie Torgersen 40.3 18 195 3250 female
# 4 Adelie Torgersen NA NA NA NA NA
# 5 Adelie Torgersen 36.7 19.3 193 3450 female
# 6 Adelie Torgersen 39.3 20.6 190 3650 male
# 7 Adelie Torgersen 38.9 17.8 181 3625 female
# 8 Adelie Torgersen 39.2 19.6 195 4675 male
# 9 Adelie Torgersen 34.1 18.1 193 3475 NA
# 10 Adelie Torgersen 42 20.2 190 4250 NA
# # ℹ 334 more rows
# # ℹ Use `print(n = ...)` to see more rows