基于R语言识别线段并定义多边形对象的技术咨询
Hey there! I see you've already got your line dataset loaded into R and are using slots to dig into the object details. Let's get you set up to count those closed lines (your potential polygons) efficiently.
Since you mentioned using Slot(), you're likely working with a SpatialLines object from the sp package. But I'll also cover the modern sf package workflow in case you're considering switching (it's more intuitive for most spatial tasks these days!).
SpatialLines (sp package) Here's how to extract coordinates, check if each line is closed, and count them:
# Load the sp package if you haven't already library(sp) # Replace `your_line_data` with the name of your SpatialLines object closed_line_check <- sapply(your_line_data@lines, function(line) { # Pull the coordinate matrix for the current line coords <- line@Lines[[1]]@coords # Compare the first and last row of coordinates (X and Y) all(coords[1, ] == coords[nrow(coords), ]) }) # Sum up how many lines are closed (potential polygons) total_potential_polygons <- sum(closed_line_check) # Print the result cat("Total number of potential polygons:", total_potential_polygons, "\n")
A quick breakdown: We loop through each Line in your SpatialLines object, grab its coordinate matrix, and check if the first and last coordinate pairs are identical. The sapply() gives us a boolean vector, which we sum to get the count.
sf objects (modern approach) If you're using the sf package (recommended for new spatial projects), here's a tidyverse-friendly way to do this:
library(sf) library(dplyr) # Replace `your_sf_lines` with your sf LINESTRING object # Extract coordinates and group by each line (L1 column tracks line IDs) closed_line_summary <- st_coordinates(your_sf_lines) %>% as.data.frame() %>% group_by(L1) %>% summarize( is_closed = first(X) == last(X) && first(Y) == last(Y) ) # Count the closed lines total_potential_polygons <- sum(closed_line_summary$is_closed) cat("Total number of potential polygons:", total_potential_polygons, "\n")
This uses st_coordinates() to get all line coordinates, groups them by each line, and checks if the first and last X/Y values match.
Keep in mind that a closed line isn't exactly a polygon yet (polygons are area features), but this count gives you the number of line features that could be converted into polygons if needed.
内容的提问来源于stack exchange,提问作者morteza

