在R中对比迁移后员工角色与映射文件的校验方案咨询
R语言员工角色迁移校验实现方案
核心思路
先通过角色映射表生成每个员工预期的新角色集合,再提取新系统中每个员工实际的新角色集合,最后对比两个集合是否完全一致(无缺失、无额外角色),输出校验状态。
假设数据结构
先明确你的数据格式(如果不符,只需调整列名即可):
olddata:含employee_ID(员工ID)、old_role(旧系统角色)newdata:含employee_ID、new_role(新系统角色)role_mapping:含old_role(旧角色)、new_role(对应需分配的新角色)
完整实现代码(推荐用dplyr+purrr,新手友好)
# 加载必要包(如果没安装先运行 install.packages(c("dplyr", "purrr"))) library(dplyr) library(purrr) # 1. 生成每个员工的预期新角色集合 expected_roles <- olddata %>% left_join(role_mapping, by = "old_role") %>% group_by(employee_ID) %>% # 排序后转列表,避免角色顺序不同导致误判 summarise(expected = list(sort(unique(new_role))), .groups = "drop") # 2. 生成每个员工的实际新角色集合 actual_roles <- newdata %>% group_by(employee_ID) %>% summarise(actual = list(sort(unique(new_role))), .groups = "drop") # 3. 对比预期与实际,输出校验结果 validation_result <- expected_roles %>% full_join(actual_roles, by = "employee_ID") %>% # 处理极端情况:旧/新数据无该员工的角色记录 mutate( expected = replace(expected, is.na(expected), list(character(0))), actual = replace(actual, is.na(actual), list(character(0))), # 逐行对比两个集合是否完全一致 status = ifelse(map2_lgl(expected, actual, identical), "ok", "not ok") ) %>% # 只保留员工ID和校验状态 select(employee_ID, status)
关键细节说明
sort():确保角色顺序不影响校验结果(比如预期是["A","B"],实际是["B","A"]会被判定为匹配)unique():避免映射表或新旧数据中出现重复角色导致集合对比出错- 缺失处理:如果某个员工在旧数据有记录但新数据无角色,或反过来,都会标记为
not ok - 兼容多旧角色场景:如果员工旧系统有多个角色(虽然你之前是单角色,但代码可扩展),会自动合并所有旧角色对应的新角色
简化版(确认单旧角色场景)
如果可以保证每个员工在olddata中只有一个旧角色,可简化代码:
library(dplyr) # 直接合并映射与新旧数据,对比集合 validation_result <- olddata %>% left_join(role_mapping, by = "old_role") %>% group_by(employee_ID) %>% summarise(expected = list(sort(new_role)), .groups = "drop") %>% full_join( newdata %>% group_by(employee_ID) %>% summarise(actual = list(sort(new_role)), .groups = "drop"), by = "employee_ID" ) %>% mutate( expected = replace(expected, is.na(expected), list(character(0))), actual = replace(actual, is.na(actual), list(character(0))), status = ifelse(mapply(identical, expected, actual), "ok", "not ok") ) %>% select(employee_ID, status)
内容的提问来源于stack exchange,提问作者xusha666
相关产品推荐
相关产品推荐

