这些是 dplyr 的 group_by()
和 ungroup()
泛型的方法。根据 arrange
参数的值,分组会转换为 [.data.table
的 keyby
和 by
参数。
用法
# S3 method for dtplyr_step
group_by(.data, ..., .add = FALSE, arrange = TRUE)
# S3 method for dtplyr_step
ungroup(x, ...)
参数
- .data
- ...
-
在
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
例子
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 dtplyr group_modify.dtplyr_step 对每个组应用一个函数
- R dtplyr lazy_dt 创建一个“惰性”data.table 以与 dplyr 动词一起使用
- R dtplyr transmute.dtplyr_step 创建新列,删除旧列
- R dtplyr slice.dtplyr_step 使用行的位置对行进行子集化
- R dtplyr left_join.dtplyr_step 连接数据表
- R dtplyr fill.dtplyr_step 用上一个或下一个值填充缺失值
- R dtplyr filter.dtplyr_step 使用列值对行进行子集化
- R dtplyr mutate.dtplyr_step 创建和修改列
- R dtplyr distinct.dtplyr_step 子集不同/唯一行
- R dtplyr unite.dtplyr_step 通过将字符串粘贴在一起将多列合并为一列。
- R dtplyr nest.dtplyr_step 巢
- R dtplyr relocate.dtplyr_step 使用变量名称重新定位变量
- R dtplyr head.dtplyr_step 对第一行或最后一行进行子集化
- R dtplyr expand.dtplyr_step 扩展 DataFrame 以包含所有可能的值组合。
- R dtplyr intersect.dtplyr_step 设置操作
- R dtplyr pivot_wider.dtplyr_step 将数据从长轴转向宽轴
- R dtplyr summarise.dtplyr_step 将每组汇总为一行
- R dtplyr count.dtplyr_step 按组计数观察值
- R dtplyr select.dtplyr_step 使用名称对列进行子集化
- R dtplyr drop_na.dtplyr_step 删除包含缺失值的行
- R dtplyr complete.dtplyr_step 完成缺少数据组合的 DataFrame
- R dtplyr collect.dtplyr_step 强制计算惰性 data.table
- R dtplyr arrange.dtplyr_step 按列值排列行
- R dtplyr separate.dtplyr_step 使用正则表达式或数字位置将字符列分成多列
- R dtplyr rename.dtplyr_step 使用名称重命名列
注:本文由纯净天空筛选整理自Hadley Wickham等大神的英文原创作品 Group and ungroup。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。