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

R语言处理经纬度数据:统一保留5位小数并修改相邻重复坐标对

R语言经纬度数据处理实现

以下代码可直接实现你要求的两个功能,首先是统一保留5位小数,其次对连续重复的经纬度对做增量偏移:

依赖包实现版本(写法更简洁)

需要用到dplyr和data.table包,其中data.table的rleid函数用来快速生成连续相同值的分组ID:

# 加载依赖
library(dplyr)
library(data.table)

# 原始数据构造
test <- data.frame(
  Latitude = c(45.14565, 45.14565, 45.14565, 45.14565, 33.2222, 31.22122, 31.22122),
  Longitude = c(-105.6666, -105.6666, -105.6666, -104.3333, -104.3333, -105.77777, -105.77777)
)

test_updated <- test %>%
  # 统一保留5位小数
  mutate(
    Latitude = round(Latitude, 5),
    Longitude = round(Longitude, 5)
  ) %>%
  # 生成连续相同经纬度对的分组ID
  mutate(group_id = rleid(Latitude, Longitude)) %>%
  # 按分组计算偏移量:组内第N行偏移(N-1)*0.00001
  group_by(group_id) %>%
  mutate(
    offset = (row_number() - 1) * 1e-5,
    Latitude = Latitude + offset,
    Longitude = Longitude + offset
  ) %>%
  ungroup() %>%
  # 移除辅助计算列
  select(-group_id, -offset)

基础R实现版本(无需额外安装包)

如果不想安装第三方包,可以用纯基础R语法实现相同逻辑:

# 原始数据构造
test <- data.frame(
  Latitude = c(45.14565, 45.14565, 45.14565, 45.14565, 33.2222, 31.22122, 31.22122),
  Longitude = c(-105.6666, -105.6666, -105.6666, -104.3333, -104.3333, -105.77777, -105.77777)
)

# 第一步:统一保留5位小数
test$Latitude <- round(test$Latitude, 5)
test$Longitude <- round(test$Longitude, 5)

# 第二步:生成连续相同经纬度对的分组ID
n <- nrow(test)
group_id <- c(1, cumsum(
  test$Latitude[-1] != test$Latitude[-n] | test$Longitude[-1] != test$Longitude[-n]
) + 1)

# 按分组计算偏移量
test_list <- split(test, group_id)
test_updated <- do.call(rbind, lapply(test_list, function(df) {
  offset <- (seq_len(nrow(df)) - 1) * 1e-5
  df$Latitude <- df$Latitude + offset
  df$Longitude <- df$Longitude + offset
  return(df)
}))
rownames(test_updated) <- NULL

补充说明

如果需要强制让数值显示5位小数(比如33.2222显示为33.22220),可以在处理完成后用sprintf("%.5f", x)将对应列转为字符格式,数值类型默认会省略末尾的0,不影响实际精度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 13:27:03