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

基于重复样带ID生成全局唯一ID的R语言数据处理问题

重复样带ID转全局唯一ID实现方案

从事动物观测研究的同事提供了多transect样带记录数据,其仅使用1、7、13、19四个ID编码重复标记不同样带,需要将这些重复ID替换为全局唯一ID,预期实现效果如下:
预期效果示意图

对应示例数据集代码如下:

example_data<-structure(list(ID_Transect = c(1L, 1L, 1L, 1L, 1L, 1L, 7L, 7L, 
                                             7L, 7L, 7L, 7L, 13L, 13L, 13L, 13L, 13L, 13L, 19L, 19L, 19L, 
                                             19L, 19L, 19L, 1L, 1L, 1L, 1L, 1L, 1L, 7L, 7L, 7L, 7L, 7L, 7L), 
                             transect_id = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 
                   2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 
                   5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L)), class = "data.frame", row.names = c(NA, 
                                                                                             -36L))

实现代码

dplyr方案(推荐,简洁高效)

要求dplyr版本≥1.1.0,直接调用consecutive_id识别连续的相同ID组生成唯一编码:

library(dplyr)
example_data <- example_data %>%
  mutate(global_transect_id = consecutive_id(ID_Transect))

基础R方案(兼容性更强)

无需安装额外包,用rle函数实现相同逻辑:

rle_result <- rle(example_data$ID_Transect)
example_data$global_transect_id <- rep(seq_along(rle_result$values), times = rle_result$lengths)

以上两种方法运行后,新增的global_transect_id列即为所需的全局唯一样带ID,和示例预期输出完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 11:36:08