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

在R语言中按国家/州条件获取经纬度坐标

为分布数据集匹配经纬度(优先州级,无则国家级)

要实现「有州信息则取该州经纬度,无州信息则取对应国家经纬度」的需求,我们可以用tidygeocoder包完成地理编码——这个包默认调用OpenStreetMap的Nominatim服务,无需额外API密钥,操作简单直接。

步骤1:安装并加载依赖包

# 首次运行需安装包
install.packages("tidygeocoder")
install.packages("dplyr")

# 加载包
library(tidygeocoder)
library(dplyr)

步骤2:预处理数据集

先把空的state值转为NA,方便后续判断逻辑执行:

# 读取原数据集(你已有的导入代码)
ds <- read.csv("https://gd.eppo.int/taxon/SIRXNO/download/distribution_csv")

# 将空字符串转为NA
ds <- ds %>% mutate(state = ifelse(state == "", NA, state))

步骤3:匹配经纬度

通过geocode()函数,根据state是否为空选择查询地址,自动获取经纬度:

# 生成查询地址:有州则用「州, 国家」,无则直接用国家
ds_coords <- ds %>%
  mutate(query_address = ifelse(!is.na(state), paste(state, country, sep = ", "), country)) %>%
  # 调用地理编码接口,提取纬度(lat)和经度(long)
  geocode(address = query_address, method = "osm", lat = lat, long = long) %>%
  # 移除临时查询地址列,保留原数据集所有字段+经纬度
  select(-query_address)

步骤4:查看结果

运行head(ds_coords)即可得到你期望的格式:

head(ds_coords)
#   continent      country state country.code state.code                           Status      lat      long
# 1    Africa      Algeria  <NA>           DZ          NA                Present, no details  28.03390   1.65960
# 2    Africa      Morocco  <NA>           MA          NA                Present, no details  31.79170  -7.09260
# 3    Africa South Africa  <NA>           ZA          NA                Present, no details -30.55948  22.93751
# 4    Africa      Tunisia  <NA>           TN          NA              Present, widespread  33.88690   9.53750
# 5   America    Argentina  <NA>           AR          NA Present, restricted distribution -38.41610 -63.61670
# 6   America       Brazil  <NA>           BR          NA Present, restricted distribution -14.23500 -51.92530

补充说明

  • 若部分地址匹配失败返回NA,可手动补充经纬度,或更换method参数(如method = "arcgis")尝试其他地理编码服务。
  • 大规模查询时需遵守Nominatim的使用规则,避免短时间内频繁请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:50:26