You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中按first列分组为数据框的唯一行组合编号

解决方案

首先构造你的示例数据:

df <- data.frame(
  first = c('A','A','B','C','A','B','B'),
  second = c(1,2,1,1,1,1,2),
  third = c(1,2,1,1,1,3,1)
)

方法一:使用dplyr包

通过分组后对唯一组合匹配编号,兼容整数/字符串类型的列:

library(dplyr)

df_result <- df %>%
  group_by(first) %>%
  # 用interaction生成唯一组合标识,比paste更稳妥,自动适配不同数据类型
  mutate(group = match(interaction(second, third), unique(interaction(second, third)))) %>%
  ungroup()

print(df_result)

方法二:使用data.table包

适合处理大数据集,运行效率更高:

library(data.table)

setDT(df)
df[, group := match(interaction(second, third), unique(interaction(second, third))), by = first]

print(df)

运行后得到的结果与预期一致:

first second third group
1     A      1     1     1
2     A      2     2     2
3     B      1     1     1
4     C      1     1     1
5     A      1     1     1
6     B      1     3     2
7     B      2     1     3

内容的提问来源于stack exchange,提问作者Lucius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 11:14:52