I am trying to take create a set of polygons from vertex locations, saved in X,Y format.
Here is an example of my data - each row represents the vertices for one polygon. the polygons are squares
square <- rbind(c(255842.4, 4111578, 255862.4, 4111578, 255862.4, 4111558,
255842.4, 4111558, 255842.4, 4111578, 255842.4, 4111578),
c(257397.0, 4111309, 257417.0, 4111309, 257417.0, 4111289,
257397.0, 4111289, 257397.0, 4111309, 257397.0, 4111309))
ID <- c("SJER1", "SJER2")'
I am using SpatialPolygons
, thus my data need to be in a list. so i created a loop to attempt to get my data into a list format from a matrix.
I create a loop following code that I found in some other questions on this site. I broke out each step to try to understand why i am only getting one polygon as the output even through I have 2 sets of points.
for (i in 1:2) {
pts <- rbind(c(square[i,1], square[i,2]), c(square[i,3], square[i,4]),
c(square[i,5],square[i,6]), c(square[i,7],square[i,8]),
c(square[i,9],square[i,10]))
sp1 <- list(Polygon(pts))
sp2 <- list(Polygons(sp1,i))
sp = SpatialPolygons(sp2)
}
plot(sp)
Can you please help me understand how I adjust the code to write out two polygons instead of just one? And also, how I assign the ID to each polygon given I am using a matrix (square) as my starting dataset and if I assign a character id, it transforms all of my data into a character.
My ultimate goal is two polygons in the SpatialPolygons
object, the first with the ID SJER1
and the second with the ID SJER2
stored in the SpatialPolygons
object.
Then I will write this out to a shapefile.
for (i in 1:2) { polys <- SpatialPolygons(list( Polygons(list(Polygon(matrix(square[i, ], ncol=2, byrow=TRUE))), ID[i]) )) }
ORa <- vector('list', length(2)) for (i in 1:2) { a[[i]]<-list( Polygons(list(Polygon(matrix(square[i, ], ncol=2, byrow=TRUE))), ID[i]) ) } SpatialPolygons(a)
don't work? i need to run this on many points so i will need some sort of loop. your time and explanation are much appreciated. i did review the documentation as well. – Conceptualism