如何在R中将数据框同ID的点转换为四组经纬度坐标对?
R中从边界点生成多边形坐标数据框的解决方案
基于给定的样本数据框(包含每个正方形的左上角(x1,y1)和右下角(x2,y2)),我们需要将其转换为每个id对应四个顶点坐标的长格式数据框。以下是几种可行的解决方案:
示例输入数据
sample_df <- data.frame(id = c(1,2), t = c('2020-01-01','2020-01-01'), intensity = c(1.3,0.6), x1 = c(113.75,114.00), x2 = c(114.00,114.25), y1 = c(8.75,8.75), y2 = c(9.00,9.00))
方法一:tidyverse工具链(dplyr + tidyr)
适合熟悉tidyverse生态的用户,代码可读性强:
library(dplyr) library(tidyr) result_df <- sample_df %>% rowwise() %>% # 为每行生成包含四个顶点坐标的列表列 mutate(coords = list(tibble(lon = c(x1, x2, x2, x1), lat = c(y1, y1, y2, y2)))) %>% # 展开列表列生成多行 unnest(coords) %>% ungroup() %>% # 调整列顺序匹配目标格式 select(id, t, intensity, lon, lat) print(result_df)
方法二:基础R实现(无需额外包)
适合不想加载第三方包的场景:
# 定义生成正方形四个顶点坐标的函数 get_square_coords <- function(x1, x2, y1, y2) { data.frame(lon = c(x1, x2, x2, x1), lat = c(y1, y1, y2, y2)) } # 按行处理并合并结果 result_df_base <- do.call(rbind, apply(sample_df, 1, function(row) { coords <- get_square_coords(as.numeric(row["x1"]), as.numeric(row["x2"]), as.numeric(row["y1"]), as.numeric(row["y2"])) cbind(row[c("id", "t", "intensity")], coords) })) # 修正数据类型(apply会将数据转为字符型,需转回对应类型) result_df_base$id <- as.integer(result_df_base$id) result_df_base$intensity <- as.numeric(result_df_base$intensity) result_df_base$lon <- as.numeric(result_df_base$lon) result_df_base$lat <- as.numeric(result_df_base$lat) print(result_df_base)
方法三:data.table实现(高效处理大数据)
适合处理大规模数据集,运行效率更高:
library(data.table) setDT(sample_df) result_df_dt <- sample_df[, .(lon = c(x1, x2, x2, x1), lat = c(y1, y1, y2, y2)), by = .(id, t, intensity)] print(result_df_dt)
以上三种方法均能生成符合要求的数据框,输出结果与目标格式完全一致。
内容的提问来源于stack exchange,提问作者cinnamoroll
相关产品推荐
相关产品推荐

