R语言如何基于location列创建含三类字符串分类的新列
tibble数据集location列分类匹配实现方案
精确匹配方案(适配预先定义好完整取值列表的场景)
首先确保你预先定义的分类匹配列表是字符向量格式,参考示例:
# 替换为你自己整理的实际取值即可 EUplus_list <- c("Germany", "France", "United Kingdom", "Italy", "Spain", "Netherlands", "Sweden", "Norway", "Switzerland") americas_list <- c("United States", "USA", "Canada", "Mexico", "Brazil", "Argentina", "Colombia")
直接用dplyr::mutate配合case_when写逻辑即可,这是处理tibble最稳定的写法,不会出现长度不匹配、取值错位的问题:
library(tidyverse) # 把df替换成你自己的数据集名称 df <- df %>% mutate( region = case_when( location %in% EUplus_list ~ "EUplus", location %in% americas_list ~ "americas", TRUE ~ "other" ) )
之前代码运行异常的常见原因
- 误用
==做批量匹配:==仅支持单值对等判断,匹配多值列表必须用%in%,否则会触发长度不匹配警告,返回结果完全错位。 - 未设置兜底规则:
case_when按顺序判断匹配,如果不写最后一行TRUE ~ "other",所有不在两个匹配列表里的取值(包括location为空的NA值)都会返回NA,不会自动归类为other。 - 未清洗格式差异:推特用户填写的location常存在前后多余空格、大小写混乱问题,比如实际值为" usa "、"france"时,会和列表里的"USA"、"France"匹配失败,可以先做一轮简单清洗再匹配:
df <- df %>% mutate( # 统一转小写、去除首尾空格 location_clean = str_to_lower(str_trim(location)), region = case_when( location_clean %in% str_to_lower(EUplus_list) ~ "EUplus", location_clean %in% str_to_lower(americas_list) ~ "americas", TRUE ~ "other" ) )
模糊匹配方案(适配location包含城市、地区后缀的场景)
如果你的location列不是纯国家/地区取值,而是类似"Paris, France"、"Brooklyn, NY, USA"这类带后缀的内容,改用关键词检测做模糊匹配即可:
df <- df %>% mutate( region = case_when( str_detect(str_to_lower(location), paste(str_to_lower(EUplus_list), collapse = "|")) ~ "EUplus", str_detect(str_to_lower(location), paste(str_to_lower(americas_list), collapse = "|")) ~ "americas", TRUE ~ "other" ) )
结果校验
跑完代码后执行count(df, region)即可查看三个分类的样本量,如果other分类占比异常高,抽取几条other类别的location取值检查,补充遗漏的匹配项即可。
内容的提问来源于stack exchange,提问作者sabrina
相关产品推荐
相关产品推荐

