R for compute the area and centroid of polygons

494 views Asked by At

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

enter image description here

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 :

enter image description here

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?

1

There are 1 answers

0
raymkchow On

The area A.sum in C.ysum and C.xsum should be the total area but not an area that depends on your iterator i. 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.

....

while(i<n+1){

  j <- ifelse(i+1==n+1,1,i+1) # j=i+1 and j=1 for the last iteration

  A.area<-0.5*(poly.d[i,2]*poly.d[j,1]-poly.d[j,2]*poly.d[i,1])
  A.sum<-A.sum+A.area

  C.x<-(poly.d[i,2]+poly.d[j,2])*(poly.d[i,2]*poly.d[j,1]-poly.d[j,2]*poly.d[i,1])
  C.xsum<-C.xsum+C.x

  C.y<-(poly.d[i,1]+poly.d[j,1])*(poly.d[i,2]*poly.d[j,1]-poly.d[j,2]*poly.d[i,1])
  C.ysum<-C.ysum+C.y

  i<-i+1
}

C.ysum<-C.ysum/(6*A.sum)
C.xsum<-C.xsum/(6*A.sum)
....