从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的列表。然后,您可以使用rbind do.call列表。但是,这也应该使用一个唯一的ID。

library(sp)

# recreating your data

data = structure(list(Id = c(7896,7896,7896),Latitude = c(-50.33766,-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)