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

如何在R中为第二分组变量分配随主分组重置的组编号

解决方案

你可以借助dplyr的分组+match()函数实现需求,该方案会严格按照每个Measurement分组内Compound首次出现的顺序生成编号,完全匹配你需要的效果:

library(dplyr)
dat_result <- dat %>%
  # 按Measurement分组,每组内编号独立重置
  group_by(Measurement) %>%
  # 匹配当前Compound在当前分组的唯一值序列中的位置,相同Compound位置一致
  mutate(Compound_order = match(Compound, unique(Compound))) %>%
  ungroup()

如果希望编号按照Compound的字典序生成,可以替换mutate行的代码为:

mutate(Compound_order = dense_rank(Compound))

基础R替代方案

如果你不想加载dplyr包,也可以用基础R的ave()函数实现相同效果:

dat$Compound_order <- ave(dat$Compound, dat$Measurement, FUN = function(x) match(x, unique(x)))

运行上述任意代码后输出的结果和你给出的预期效果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:36:04