dplyr `rowwise()` 的分组方式是否与 `group_by()` 分组的方式相同?

Does dplyr `rowwise()` group in the same way `group_by()` groups?

library(tidyverse)
mtcars %>% group_by(cyl) %>% is_grouped_df()
#> [1] TRUE

我可以按变量对数据框进行分组,并使用 is_grouped_df() 函数(如上所示)确认它是否已分组。

我可以 运行 对 dplyr rowwise() 函数进行相同的分析,而且 rowwise() 似乎没有按行对数据集进行分组。我有一个问题,阅读帮助页面 (?rowwise) 并没有清楚地回答我的问题。

Group input by rows

Description: rowwise() allows you to compute on a data frame a row-at-a-time. This is most useful when a vectorised function doesn't exist.

A row-wise tibble maintains its row-wise status until explicitly removed by group_by(), ungroup(), or as_tibble().

我的问题:调用 rowwise() 函数后,我是否需要稍后在我的管道中调用 ungroup() 函数来取消分组我的数据集?或者这是默认完成的?以下管道表明包含 rowwise() 的管道未分组:

mtcars %>% rowwise() %>% is_grouped_df()
#> [1] FALSE

这句话让我感到困惑,“A row-wise tibble 保持其 row-wise 状态,直到被... ungroup()... 明确删除”。为什么我需要 ungroup() 一个已经取消分组的小标题?

有趣的观察。这可能是 is_grouped_df 的错误,除非它是我不知道的某种功能。但我确实认为 ungroup 考虑下面所做的测试很重要(见评论):

library(tidyverse)

mtcars %>% select(1:3) %>% rowwise() %>% head(2)
#> Source: local data frame [2 x 3]
#> Groups: <by row>
##### ^ THIS DOES HAVE A GROUP ####
#> 
#> # A tibble: 2 x 3
#>     mpg   cyl  disp
#>   <dbl> <dbl> <dbl>
#> 1    21     6   160
#> 2    21     6   160

mtcars %>% select(1:3) %>% rowwise() %>% mutate(n()) %>% head(2)
#> Source: local data frame [2 x 4]
#> Groups: <by row>
#> 
#> # A tibble: 2 x 4
#>     mpg   cyl  disp `n()`
#>   <dbl> <dbl> <dbl> <int>
#> 1    21     6   160     1
#> 2    21     6   160     1
mtcars %>% select(1:3) %>% mutate(n()) %>% head(2)                                              
#>   mpg cyl disp n()
#> 1  21   6  160  32
#> 2  21   6  160  32

##### ^ THIS IS EXPECTED AND THE n BEHAVES DIFFERENTLY WHEN THE ROWWISE() IS APPLIED ####

##### IF WE WANT TO RESTORE "NORMAL" BEHAVIOR, IT'S PROBABLY WISE TO UNGROUP IN ORDER TO LOSE THE ROWWISE OPERATIONS #####
mtcars %>% select(1:3) %>% rowwise() %>% ungroup %>% mutate(n()) %>% head(2)
#> # A tibble: 2 x 4
#>     mpg   cyl  disp `n()`
#>   <dbl> <dbl> <dbl> <int>
#> 1    21     6   160    32
#> 2    21     6   160    32

## ^ NORMAL AFTER UNGROUP