# 在 R Dplyr 中使用 group_by 函数

Jesse John 2023年1月30日

`dplyr` 包的 `group_by()` 函数帮助我们根据不同列中的值对行进行分组。然后，我们可以使用这些组来创建摘要、选择特定组进行进一步分析，或者根据组属性创建新列。

## 在 R 中设置 `dplyr` 包

``````# Install dplyr. Or install the tidyverse.
# UNCOMMENT THE FOLLOWING LINE TO INSTALL.
# install.packages("dplyr")

library(dplyr)

# Create vectors.
set.seed(11)
Col_code = sample(2200:7200, 10, replace=FALSE)
set.seed(222)
Col_one = sample(c("RD", "GN", "YW"), 10, replace = TRUE)
set.seed(4444)
Col_two = sample(c(3, 6), 10, replace = TRUE)

# Create a tibble.
my_t = tibble(Col_code, Col_one, Col_two)

# View the tibble.
my_t
``````

## 在 R 中使用 `group_by()` 函数

``````# Use group_by().
group_by(my_t, Col_two)
``````

``````# A tibble: 10 x 3
# Groups:   Col_two [2]
Col_code Col_one Col_two
<int> <chr>     <dbl>
1     3985 RD            6
2     2233 GN            6
3     2895 YW            6
4     3120 GN            6
5     6439 YW            3
6     4819 GN            6
7     2573 GN            6
8     5484 RD            6
9     6509 GN            3
10     4309 RD            3
``````

## 在 R 中使用 `group_by()` 和 `summarize()`

``````# Group by one column.
my_t %>% group_by(Col_two) %>% summarize(n())
``````

``````# A tibble: 2 x 2
Col_two `n()`
<dbl> <int>
1       3     3
2       6     7
``````

``````# Group by more than one column.
my_t %>% group_by(Col_one, Col_two) %>% summarize(Num_Rows = n())
``````

``````# A tibble: 6 x 3
# Groups:   Col_one [3]
Col_one Col_two Num_Rows
<chr>     <dbl>    <int>
1 GN            3        1
2 GN            6        4
3 RD            3        1
4 RD            6        2
5 YW            3        1
6 YW            6        1
``````

`summarize()` 函数可以计算多个组统计数据，例如 `mean`

``````# Calculate the mean.
# The output has 3 significant digits by default.
my_t %>% group_by(Col_one, Col_two) %>% summarize(mean(Col_code))

# Convert the output to a data frame to see the decimal places.
my_t %>% group_by(Col_one, Col_two) %>% summarize(mean(Col_code)) %>% as.data.frame()
``````

``````> my_t %>% group_by(Col_one, Col_two) %>% summarize(mean(Col_code))
`summarise()` has grouped output by 'Col_one'. You can override using the `.groups` argument.
# A tibble: 6 x 3
# Groups:   Col_one [3]
Col_one Col_two `mean(Col_code)`
<chr>     <dbl>            <dbl>
1 GN            3            6509
2 GN            6            3186.
3 RD            3            4309
4 RD            6            4734.
5 YW            3            6439
6 YW            6            2895

> # Convert the output to a data frame to see the decimal places.
> my_t %>% group_by(Col_one, Col_two) %>% summarize(mean(Col_code)) %>% as.data.frame()
`summarise()` has grouped output by 'Col_one'. You can override using the `.groups` argument.
Col_one Col_two mean(Col_code)
1      GN       3        6509.00
2      GN       6        3186.25
3      RD       3        4309.00
4      RD       6        4734.50
5      YW       3        6439.00
6      YW       6        2895.00
``````

``````library(tibble)
my_t %>% group_by(Col_one, Col_two) %>% summarize(tMean = num(mean(Col_code),digits=-2))
``````

``````# A tibble: 6 x 3
# Groups:   Col_one [3]
Col_one Col_two    tMean
<chr>     <dbl> <num:.2>
1 GN            3  6509
2 GN            6  3186.25
3 RD            3  4309
4 RD            6  4734.5
5 YW            3  6439
6 YW            6  2895
``````

``````# Create a tibble with two levels of groupings.
tib_2_gr = my_t %>% group_by(Col_one, Col_two)

# Check that the tibble is grouped by two variables.
group_vars(tib_2_gr)

# Use the summarize() function once.
tib_1_gr = my_t %>% group_by(Col_one, Col_two) %>% summarize(Num_Rows = n())

# Check that the new tibble is grouped by only one variable after using summarize().
group_vars(tib_1_gr)
``````

``````> group_vars(tib_2_gr)
[1] "Col_one" "Col_two"

> group_vars(tib_1_gr)
[1] "Col_one"
``````

## 在 R 中使用 `group_by()` 和 `filter()`

``````# Create a tibble with groups.
t_fil = my_t %>% group_by(Col_one, Col_two)

# Remove rows where Col_one is 'RD'.
t_fil %>% filter(Col_one != "RD")
``````

``````# A tibble: 7 x 3
# Groups:   Col_one, Col_two [4]
Col_code Col_one Col_two
<int> <chr>     <dbl>
1     2233 GN            6
2     2895 YW            6
3     3120 GN            6
4     6439 YW            3
5     4819 GN            6
6     2573 GN            6
7     6509 GN            3
``````

``````# First summarize.
t_fil %>% summarize(AVE = num(mean(Col_code), digits=-2))

# Now filter the summarized data.
# We will provide the new summary column to the filter function.
t_fil %>% summarize(AVE = num(mean(Col_code), digits=-2)) %>% filter(AVE > 4000)
``````

``````# A tibble: 4 x 3
# Groups:   Col_one [3]
Col_one Col_two      AVE
<chr>     <dbl> <num:.2>
1 GN            3   6509
2 RD            3   4309
3 RD            6   4734.5
4 YW            3   6439
``````

## 在 R 中使用 `group_by()` 和 `mutate()`

``````# Group data.
t_mut = my_t %>% group_by(Col_one)

# Mutate based on grouping.
t_mut %>% mutate(MIN_GR_CODE = min(Col_code)) %>% arrange(.by_group = TRUE)

# If we use summarize(), we do not get the columns that were not grouped.
t_mut %>% summarize(MIN_GR_CODE = min(Col_code))
``````

``````> # Mutate based on grouping.
> t_mut %>% mutate(MIN_GR_CODE = min(Col_code)) %>% arrange(.by_group = TRUE)
# A tibble: 10 x 4
# Groups:   Col_one [3]
Col_code Col_one Col_two MIN_GR_CODE
<int> <chr>     <dbl>       <int>
1     2233 GN            6        2233
2     3120 GN            6        2233
3     4819 GN            6        2233
4     2573 GN            6        2233
5     6509 GN            3        2233
6     3985 RD            6        3985
7     5484 RD            6        3985
8     4309 RD            3        3985
9     2895 YW            6        2895
10     6439 YW            3        2895

> # If we use summarize(), we do not get the columns that were not grouped.
> t_mut %>% summarize(MIN_GR_CODE = min(Col_code))
# A tibble: 3 x 2
Col_one MIN_GR_CODE
<chr>         <int>
1 GN             2233
2 RD             3985
3 YW             2895
``````

## 在 R 中取消组合 tibble

``````# View a grouped tibble.
tib_2_gr
# The grouping is mentioned as the second line in the output.

# We can also check the grouping using the group_vars() function.
group_vars(tib_2_gr)

# ungroup() the tibble.
ungroup(tib_2_gr)

# Check the groups.
group_vars(tib_2_gr)
# The groups are still there because we did not save the change.

# Save to the same object name.
tib_2_gr = ungroup(tib_2_gr)

# Now check the groupings.
group_vars(tib_2_gr)
# There is no grouping.
``````

``````> # Save to the same object name.
> tib_2_gr = ungroup(tib_2_gr)
>
> # Now check the groupings.
> group_vars(tib_2_gr)
character(0)
``````

## 参考

Jesse is passionate about data analysis and visualization. He uses the R statistical programming language for all aspects of his work.