当列为非数字时按 R data.table 中的组聚合

Aggregating by group in R data.table when column is non-numeric

我的数据集如下所示:

id | X | Y
1  | 5 | a
1  | 6 | a
1  | 9 | a
2  | 2 | f
2  | 6 | f

Y 是组 id 中相同的字符串或因子。在 data.table 中,我尝试按组汇总并得出一些统计数据,例如 Xid 的平均值。我也想得到Y。最终结果将是

id | X    | Y
1  | 6.66 | a
2  | 4    | f

如果没有 factor/string 个变量,我在 data.table 中执行此操作的方法是 dt[,.(X = mean(X)), by = .(id)]。如果 Y 是一个在组内相同的数字变量,我也可以使用 max, min, mean

例如,如何获得每个组的第一个观察值?我知道我可以执行两个单独的命令,一个用于所有数字变量,一个用于仅 strings/factors 按组获取他们的第一个观察值,然后合并。但是我想知道是否有一种方法可以在一个命令中完成。

data.table

中有一个first函数
library(data.table)
dt[, .(X = mean(X), Y = first(Y)), by = .(id)]

或者可以简单地使用索引 [1]

dt[, .(X = mean(X, na.rm = TRUE), Y = Y[1]), by = .(id)]

根据显示的数据,'Y'值也可以用于分组

dt[, .(X = mean(X, na.rm = TRUE)), by = .(id, Y)]

如果有多个 numeric/character/factor 列,请使用 if/else 条件

dt[, lapply(.SD, function(x) if(is.numeric(x)) 
            mean(x, na.rm = TRUE) else first(x)), by = .(id)]

有了tidyverse,我们可以做到

library(dplyr)
dt %>%
    group_by(id) %>%
    mutate(across(where(is.numeric), mean, na.rm = TRUE),
           across(where(~ is.character(.)|| is.factor(.)), first))