如何将列表中的多个SpatialPolygonsDataFrame合并为单个sp对象?
Perfect use case—let’s work through a scalable way to merge your polygons into one SpatialPolygonsDataFrame, plus handle the duplicate polygon you mentioned.
Step 1: Load Your Data
First, read in your list of spatial objects like you already have:
list_of_spdf <- unlist(readRDS("data.Rds"))
Step 2: Automate the Merge (No Manual rbind)
Instead of writing out each list element one by one, we can automate this for any length of list:
# Extract the core polygon component from each entry in the list all_polygons <- lapply(list_of_spdf, function(spdf_entry) { spdf_entry@polygons[[1]] }) # Combine all polygons into a single SpatialPolygons object (keep original projection) merged_spatial_polygons <- SpatialPolygons( all_polygons, proj4string = list_of_spdf[[1]]@proj4string ) # Convert to SpatialPolygonsDataFrame (add a simple attribute data frame) one_spdf <- SpatialPolygonsDataFrame( merged_spatial_polygons, data = data.frame( polygon_id = seq_along(all_polygons), row.names = row.names(merged_spatial_polygons) ) )
Step 3: Remove Duplicate Polygons
Since you noted the third polygon is a repeat, we can filter out duplicates by comparing their coordinate data:
# Flag unique polygons by checking their coordinate sets unique_polygon_indices <- !duplicated( lapply(all_polygons, function(poly) { poly@Polygons[[1]]@coords }) ) # Keep only unique polygons unique_polygons <- all_polygons[unique_polygon_indices] # Create your final deduplicated SpatialPolygonsDataFrame one_spdf_unique <- SpatialPolygonsDataFrame( SpatialPolygons(unique_polygons, proj4string = list_of_spdf[[1]]@proj4string), data = data.frame( polygon_id = seq_along(unique_polygons), row.names = row.names(SpatialPolygons(unique_polygons)) ) )
Quick Note on Your Current Code
Your manual rbind approach works for small lists, but it’s not scalable if your list grows longer. The method above handles any number of entries automatically, and the duplicate check ensures you don’t carry redundant polygons into your final output.
内容的提问来源于stack exchange,提问作者jpinelo

