R语言:调研数据Job Title与Industry列分类整理问题求助
解决方案
一、Job Title列的CEO统一替换
你当前的gsub写法通过枚举大小写变体的方式不够高效,且无法覆盖所有包含CEO(大小写不限)的场景(如带空格、/、&等特殊字符的情况)。可以通过不区分大小写的匹配+条件替换实现全覆盖:
# 只要单元格包含CEO(大小写不限),就替换为"CEO" aiprm$job_title <- ifelse(grepl("ceo", aiprm$job_title, ignore.case = TRUE), "CEO", aiprm$job_title)
说明:
grepl("ceo", ..., ignore.case = TRUE):不区分大小写检测单元格是否包含"ceo"相关字符,覆盖所有大小写组合(如CEO、Ceo、cEO等)以及周围带特殊字符的情况(如CEO /、CEO&等)。ifelse:满足条件的单元格直接替换为"CEO",不满足的保留原内容。
二、Industry列的标准分类映射
可以使用dplyr包的case_when函数,结合不区分大小写的匹配,批量完成词汇到标准分类的映射:
步骤1:加载依赖包
library(dplyr)
步骤2:执行分类映射
aiprm$Industry <- case_when( # 匹配Marketing相关词汇 grepl("marketing|advertising|advertisement", aiprm$Industry, ignore.case = TRUE) ~ "Marketing", # 匹配Artificial Intelligence相关词汇 grepl("IA|artificial intelligence", aiprm$Industry, ignore.case = TRUE) ~ "Artificial Intelligence", # 匹配Finance相关词汇 grepl("finance|banking|financial", aiprm$Industry, ignore.case = TRUE) ~ "Finance", # 匹配Freelance相关词汇 grepl("free lance|freelancer|remote", aiprm$Industry, ignore.case = TRUE) ~ "Freelance", # 匹配Information Technology相关词汇 grepl("IT", aiprm$Industry, ignore.case = TRUE) ~ "Information Technology", # 未匹配到的内容保留原值(可替换为"Other"统一归类) TRUE ~ aiprm$Industry )
说明:
- 每个
grepl规则都启用了ignore.case = TRUE,自动忽略大小写差异(如IT、it、It都会被匹配)。 - 若需要将未匹配的行业统一归类为“其他”,只需把最后一行的
aiprm$Industry替换为"Other"即可。
内容的提问来源于stack exchange,提问作者Humberto R
相关产品推荐
相关产品推荐

