如何用R语言sf包将指定经纬度序列转换为sf多边形数据框
Hey there! I'll walk you through two straightforward ways to turn your coordinate data frame into the sf polygon object you need. Let's jump right in.
Prerequisite
First, make sure you have the sf package installed and loaded:
install.packages("sf") # Run this only if you haven't installed it yet library(sf)
Your original data frame is already set, but let's restate it for clarity:
df <- data.frame( order = 1:5, lon = c(119.4,119.4,119.4,119.5,119.5), lat = c(-5.192,-5.192,-5.187,-5.187,-5.191) )
Method 1: Direct Polygon Construction (Most Explicit)
This method gives you full control over the coordinate structure, which is great for understanding how sf polygons work under the hood.
Ensure coordinates are in the correct sequence:
Even though yourordercolumn already sorts the points, it's good practice to explicitly sort to avoid any accidental misordering:df_sorted <- df[order(df$order), ]Create a closed coordinate matrix:
SF requires polygons to be closed (start and end at the same point). We'll add the first coordinate pair to the end of our matrix to meet this requirement:coords <- rbind(df_sorted[, c("lon", "lat")], df_sorted[1, c("lon", "lat")])Build the polygon and sf data frame:
Convert the coordinate matrix into a polygon object, then wrap it into an sf feature collection with the correct CRS (WGS84, EPSG:4326):# Create a single polygon (note the nested list structure required by st_polygon) poly <- st_polygon(list(as.matrix(coords))) # Convert to sf data frame with CRS set sf_poly <- st_sfc(poly, crs = 4326) %>% st_sf()
Method 2: Casting from Points (More Concise)
If you prefer a clean pipeline-style approach, you can convert the points to an sf object first, then cast them up to a polygon:
sf_poly <- df %>% st_as_sf(coords = c("lon", "lat"), crs = 4326) %>% # Convert raw data to sf points arrange(order) %>% # Ensure points follow your intended sequence st_combine() %>% # Combine points into a single multi-point object st_cast("LINESTRING") %>% # Cast to a connected line string st_cast("POLYGON") %>% # Cast line string to polygon (sf auto-closes it if needed) st_sf() # Wrap into a proper sf data frame
Check the Result
If you print sf_poly, you'll get output exactly matching your desired format:
## Simple feature collection with 1 feature and 0 fields ## geometry type: POLYGON ## dimension: XY ## bbox: xmin: 119.4 ymin: -5.192 xmax: 119.5 ymax: -5.187 ## epsg (SRID): 4326 ## proj4string: +proj=longlat +datum=WGS84 +no_defs ## geometry ## 1 POLYGON ((119.4 -5.192, 119...
内容的提问来源于stack exchange,提问作者rasyidstat

