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

R语言使用countrycode包匹配国家所属大洲时返回NA问题求助

问题原因
  • countrycode()的sourcevar参数要求传入待匹配的国家名称向量,你的代码中传入了字符串'country',而非数据框内实际的country列向量,函数无法识别待匹配内容,因此统一返回NA。
  • 若你的核心需求是匹配国家所属大洲,destination = 'region'会返回更细分的次区域(如南美洲、东欧),可替换为destination = 'continent'直接获取大洲归属。
修复后代码

首先确保已加载对应依赖包:

library(dplyr)
library(countrycode)

country <- data.frame(country = c("Chile", "Argentina", "Poland"))

版本1:匹配所属大洲

country %>%
  mutate(continent = countrycode(sourcevar = country, origin = 'country.name', destination = 'continent'))

运行输出结果:

country continent
1     Chile  Americas
2 Argentina  Americas
3    Poland    Europe

版本2:匹配细分次区域

country %>%
  mutate(region = countrycode(sourcevar = country, origin = 'country.name', destination = 'region'))

运行输出结果:

country        region
1     Chile South America
2 Argentina South America
3    Poland Eastern Europe
补充说明

如果遇到特殊拼写的国家名匹配失败返回NA的情况,可以通过custom_match参数手动配置自定义映射规则,示例如下:

country %>%
  mutate(continent = countrycode(sourcevar = country, origin = 'country.name', destination = 'continent',
                                 custom_match = c('自定义国名' = '对应大洲')))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:54:00