當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


R dtplyr group_by.dtplyr_step 分組和取消分組

這些是 dplyr 的 group_by()ungroup() 泛型的方法。根據 arrange 參數的值,分組會轉換為 [.data.tablekeybyby 參數。

用法

# S3 method for dtplyr_step
group_by(.data, ..., .add = FALSE, arrange = TRUE)

# S3 method for dtplyr_step
ungroup(x, ...)

參數

.data

lazy_dt()

...

group_by() 中,用於分組的變量或計算。計算始終在未分組的數據幀上完成。要對分組數據執行計算,您需要在 group_by() 之前使用單獨的 mutate() 步驟。 nest_by() 中不允許進行計算。在 ungroup() 中,要從分組中刪除的變量。

.add, add

FALSE 時,默認情況下,group_by() 將覆蓋現有組。要添加到現有組,請使用 .add = TRUE

該參數以前稱為 add ,但這阻止了創建名為 add 的新分組變量,並且與我們的命名約定衝突。

arrange

如果是 TRUE ,會自動按組排列後續分組操作的輸出。如果是 FALSE ,輸出順序將保持不變。在生成的 data.table 代碼中,它在使用 keyby ( TRUE ) 和 by ( FALSE ) 參數之間切換。

x

tbl()

例子

library(dplyr, warn.conflicts = FALSE)
dt <- lazy_dt(mtcars)

# group_by() is usually translated to `keyby` so that the groups
# are ordered in the output
dt %>%
 group_by(cyl) %>%
 summarise(mpg = mean(mpg))
#> Source: local data table [3 x 2]
#> Call:   `_DT15`[, .(mpg = mean(mpg)), keyby = .(cyl)]
#> 
#>     cyl   mpg
#>   <dbl> <dbl>
#> 1     4  26.7
#> 2     6  19.7
#> 3     8  15.1
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results

# use `arrange = FALSE` to instead use `by` so the original order
# or groups is preserved
dt %>%
 group_by(cyl, arrange = FALSE) %>%
 summarise(mpg = mean(mpg))
#> Source: local data table [3 x 2]
#> Call:   `_DT15`[, .(mpg = mean(mpg)), by = .(cyl)]
#> 
#>     cyl   mpg
#>   <dbl> <dbl>
#> 1     6  19.7
#> 2     4  26.7
#> 3     8  15.1
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results
源代碼:R/step-group.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Group and ungroup。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。