在R语言中实现多列数据匹配的技术咨询(含Contacts2数据集示例)
Hey there! Let's tackle this contact dataset task you've got. You mentioned Contacts2 has 100k records with name, title, and columns for job type categories (Finance, Executive, Communications) that are currently NA. First, let's formalize your sample data in R code so we can work with it:
# 构建示例联系人数据集 First <- c("George","Thomas","James","Jimmy","Howard","Herbert") Last <- c("Washington", "Jefferson", "Madison", "Carter", "Taft", "Hoover") Title <- c("CEO", "Accountant","Communications Specialist", "President", "Accountant", "CFO") Finance <- rep(NA, 6) Executive <- rep(NA, 6) Communications <- rep(NA, 6) Contacts_sample <- data.frame(First, Last, Title, Finance, Executive, Communications)
核心思路:根据职位标题映射到工作类型
The goal here is to populate those NA columns by matching each Title to its corresponding job category. For a 100k-row dataset, we need an efficient approach—no slow loops!
1. 先定义职位到分类的映射规则
First, let's outline which titles fall into each category (you can tweak this to match your actual data's job titles):
- Executive (高管): CEO, President, CFO
- Finance (财务): Accountant
- Communications (沟通/公关): Communications Specialist
We can store this mapping in a list for easy reference:
title_mapping <- list( Executive = c("CEO", "President", "CFO"), Finance = c("Accountant"), Communications = c("Communications Specialist") )
2. 批量填充分类列(高效版)
Using dplyr for vectorized operations will handle 100k rows smoothly. Here's how to fill each category column with TRUE/FALSE based on the title match:
library(dplyr) Contacts_processed <- Contacts_sample %>% mutate( Executive = ifelse(Title %in% title_mapping$Executive, TRUE, FALSE), Finance = ifelse(Title %in% title_mapping$Finance, TRUE, FALSE), Communications = ifelse(Title %in% title_mapping$Communications, TRUE, FALSE) )
If you need fuzzy matching (e.g., any title containing "Account" should count as Finance), swap in grepl for regex-based matching:
Contacts_processed <- Contacts_sample %>% mutate( Executive = grepl("CEO|President|CFO", Title, ignore.case = TRUE), Finance = grepl("Account", Title, ignore.case = TRUE), Communications = grepl("Communications", Title, ignore.case = TRUE) )
3. 检查处理结果
Run this to see how the sample data turns out:
print(Contacts_processed)
You'll get output like this:
First Last Title Finance Executive Communications 1 George Washington CEO FALSE TRUE FALSE 2 Thomas Jefferson Accountant TRUE FALSE FALSE 3 James Madison Communications Specialist FALSE FALSE TRUE 4 Jimmy Carter President FALSE TRUE FALSE 5 Howard Taft Accountant TRUE FALSE FALSE 6 Herbert Hoover CFO FALSE TRUE FALSE
额外提示
If your dataset has more title variations (like "Senior Accountant" or "VP of Communications"), just expand the keywords in title_mapping or adjust the regex patterns to cover them. The vectorized operations in dplyr will handle the 100k rows without any performance issues.
内容的提问来源于stack exchange,提问作者Danny

