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

求助:在R语言中检测DataFrame分组内后缀匹配的模式偏差

解决id2列分组格式不一致的问题

嗨,我来帮你搞定这个需求!你想要识别出DataFrame里,属于同一数字后缀分组但格式不符合预期的记录,对吧?比如test_0002和test_002其实都是对应数字0002的分组,但后者格式不对。下面用R的dplyr和stringr包来实现:

第一步:提取统一的数字标识

首先我们要从id2里提取出纯数字部分,并且统一格式(比如补前导零到固定长度),这样就能把本质属于同一分组的记录归到一起:

library(dplyr)
library(stringr)

# 你的原始数据
sample <- structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 ), id2 = c("test_0001", "test_0001", "test_0001", "test_001", "test_001", "test 0001", "test001", "test_0001", "test_0001", "test_0002", "test_0002", "test_0002", "test_0002", "test_0002", "test_002", "test_002", "test_00003", "test_0003", "test_00003", "test_0003", "test 00003", "test_00004", "test_00004", "test_00004", "test_00004", "test_0004", "test_0004", "test_00004")), class = "data.frame", row.names = c(NA, -28L))

# 处理数据:提取数字、统一格式、生成预期格式
sample_processed <- sample %>%
  mutate(
    # 从id2中提取所有数字字符
    num_raw = str_extract(id2, "\\d+"),
    # 统一补前导零到4位,让001变成0001,002变成0002
    standard_num = str_pad(num_raw, width = 4, side = "left", pad = "0"),
    # 定义预期的标准格式(比如test_加4位数字,你可以根据需求修改)
    expected_id2 = str_c("test_", standard_num)
  )

第二步:标记不符合预期的记录

接下来我们可以直接对比每条记录的id2和生成的expected_id2,找出不匹配的异常记录:

# 标记异常
sample_processed <- sample_processed %>%
  mutate(is_abnormal = id2 != expected_id2)

# 查看所有异常记录
filter(sample_processed, is_abnormal)

运行这段代码后,你就能看到所有格式不符合test_XXXX的记录,包括你提到的id15、16(test_002 vs 预期test_0002),还有其他比如test_001、test 0001这类格式不对的记录。

可选:基于分组内多数格式标记异常

如果你的“预期格式”不是固定的test_XXXX,而是每个数字分组里出现次数最多的格式,比如某个分组里大部分是test_00003,那少数的test_0003就会被标记为异常,可以用下面的代码:

sample_processed <- sample_processed %>%
  group_by(standard_num) %>%
  mutate(
    # 找出当前分组中出现次数最多的格式
    most_common_format = names(which.max(table(id2))),
    is_abnormal = id2 != most_common_format
  ) %>%
  ungroup()

# 查看异常记录
filter(sample_processed, is_abnormal)

这样就能灵活适配不同分组的主流格式啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:57:47