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

如何用R基于经纬度范围创建city列,标记上海区域内企业

用R根据经纬度判断企业所属城市(以上海为例)

方法1:基础R实现

直接通过逻辑索引给新列赋值,无需额外加载包:

# 初始化city列为NA
your_data$city <- NA

# 给符合上海经纬度范围的行赋值"上海"
your_data$city[your_data$longitude >= 120.852326 & your_data$longitude <= 122.118227 &
                 your_data$latitude >= 30.691701 & your_data$latitude <= 31.874634] <- "上海"

方法2:dplyr(tidyverse)实现

语法更直观,方便后续扩展其他城市的判断:

# 首次使用需先安装dplyr包
# install.packages("dplyr")
library(dplyr)

# 生成city列
your_data <- your_data %>%
  mutate(city = case_when(
    longitude >= 120.852326 & longitude <= 122.118227 &
      latitude >= 30.691701 & latitude <= 31.874634 ~ "上海",
    # 可在此添加其他城市的判断规则,示例:
    # longitude >= xxx & longitude <= xxx & latitude >= xxx & latitude <= xxx ~ "北京",
    TRUE ~ NA_character_  # 不满足条件时返回NA
  ))

注意事项

  • 请将代码中的your_data替换为你实际使用的数据框名称
  • 确认longitude和latitude列是数值型格式,而非字符型
  • 若要识别更多城市,只需在case_when中追加对应经纬度区间的判断逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:36:11