从 R 中的经纬度列表创建多边形
Creating polygons from a list of lat long in R
我有一个包含 Id、lat 和 long 的超过 500k 行的列表,如下所示:
Id Latitude Longitude
1 7896 -50.33766 -22.23764
2 7896 -50.33768 -22.23767
3 7896 -50.33768 -22.23768
4 7896 -50.33770 -22.23775
我需要根据 Id 创建一个多边形几何体,每个几何体构成不同的多边形。
如何使用此数据创建 SpatialPolygonDataFrame?
有人可以帮助我吗?
谢谢。
考虑到您在数据的 Id
列中有多个唯一值,您可以对每个值应用一个函数来创建 SpatialPolygonsDataFrame
的列表。然后,您可以使用 do.call
rbind
列表。但是,这也适用于一个唯一的 ID。
library(sp)
# recreating your data
data = structure(list(Id = c(7896, 7896, 7896, 7896),
Latitude = c(-50.33766, -50.33768, -50.33768, -50.3377),
Longitude = c(-22.23764, -22.23767, -22.23768, -22.23775)),
class = "data.frame", row.names = c(NA, -4L))
# Applying a function to each unique value in the Id column of data
poly_list <- sapply(unique(data$Id), function(x){
# create a polygon for each unique Id
poly = Polygon(data[data$Id == x, 3:2]) # or Polygon(data[data$Id == x, c('Longitude', 'Latitude')])
# create a spatial polygon from the polygon
polys = SpatialPolygons(list(Polygons(list(poly), ID = x)))
# convert the spatial polygons to spatial polygons dataframe
as(polys, 'SpatialPolygonsDataFrame')
})
# rbind the list of spatial polygons dataframe
poly_list <- do.call(rbind, poly_list)
# visualize
plot(poly_list)
我有一个包含 Id、lat 和 long 的超过 500k 行的列表,如下所示:
Id Latitude Longitude
1 7896 -50.33766 -22.23764
2 7896 -50.33768 -22.23767
3 7896 -50.33768 -22.23768
4 7896 -50.33770 -22.23775
我需要根据 Id 创建一个多边形几何体,每个几何体构成不同的多边形。
如何使用此数据创建 SpatialPolygonDataFrame?
有人可以帮助我吗?
谢谢。
考虑到您在数据的 Id
列中有多个唯一值,您可以对每个值应用一个函数来创建 SpatialPolygonsDataFrame
的列表。然后,您可以使用 do.call
rbind
列表。但是,这也适用于一个唯一的 ID。
library(sp)
# recreating your data
data = structure(list(Id = c(7896, 7896, 7896, 7896),
Latitude = c(-50.33766, -50.33768, -50.33768, -50.3377),
Longitude = c(-22.23764, -22.23767, -22.23768, -22.23775)),
class = "data.frame", row.names = c(NA, -4L))
# Applying a function to each unique value in the Id column of data
poly_list <- sapply(unique(data$Id), function(x){
# create a polygon for each unique Id
poly = Polygon(data[data$Id == x, 3:2]) # or Polygon(data[data$Id == x, c('Longitude', 'Latitude')])
# create a spatial polygon from the polygon
polys = SpatialPolygons(list(Polygons(list(poly), ID = x)))
# convert the spatial polygons to spatial polygons dataframe
as(polys, 'SpatialPolygonsDataFrame')
})
# rbind the list of spatial polygons dataframe
poly_list <- do.call(rbind, poly_list)
# visualize
plot(poly_list)