Create functions to compute the area and centroid of a polygon list (as in the format of georgia.polys). The formula for the area of a polygon is
where A is the polygon area, xi is the i th x-coordinate of the polygon boundary (x[i] in R), yi is the i th y-coordinate of the polygon boundary (y[i] in R) - and n is the number of points used to specify the polygon boundary. The polygon is assumed to be in closed form so that the xi and yi take the same value as xn and yn. The centroid has coordinates (Cx, Cy) where :
Here is the code that already created, but im not sure the centroid coordinate is correct
library(GISTools)
data("georgia")
polyn<-function(x){
poly.df<-data.frame()
for(d in 1:159){
poly.d<-x[[d]]
n<-length(poly.d[,1])
i<-1
A.sum<-0
C.xsum<-0
C.ysum<-0
while(i<n){
A.area<-0.5*(poly.d[i,2]*poly.d[i+1,1]-poly.d[i+1,2]*poly.d[i,1])
A.sum<-A.sum+A.area
C.x<-(1/(6*A.sum))*(poly.d[i,2]+poly.d[i+1,2])*(poly.d[i,2]*poly.d[i+1,1]-poly.d[i+1,2]*poly.d[i,1])
C.xsum<-C.xsum+C.x
C.y<-(1/(6*A.sum))*(poly.d[i,1]+poly.d[i+1,1])*(poly.d[i,2]*poly.d[i+1,1]-poly.d[i+1,2]*poly.d[i,1])
C.ysum<-C.ysum+C.y
i<-i+1
}
poly.df<-rbind(poly.df, c(A.sum,C.xsum,C.ysum))
colnames(poly.df) <- c("Area", "Cx", "Cy")
}
poly.df
}
polyn(georgia.polys)
This is some result of that function,
Area Cx Cy
1 1326077000 4044403.4 4855396.03
2 891511462 -2237689.5 -2962558.41
3 740601936 10709355.7 12996988.27
Is there anyone can help me with the code?
The area
A.sum
inC.ysum
andC.xsum
should be the total area but not an area that depends on your iteratori
. The easiest way is the put the division after the calculation of area.Also, the equations should loop over the indices
1,2,...,n+1
, with the last vertex the same as the first vertex. Therefore, you should also modify your code so that it loops over the last case in the summations of the equations.