Calculating weighted polygon centroids in R

前端 未结 4 1470
小鲜肉
小鲜肉 2021-01-02 11:55

I need to calculate the centroids of a set of spatial zones based on a separate population grid dataset. Grateful for a steer on how to achieve this for the example below.<

4条回答
  •  旧时难觅i
    2021-01-02 12:30

    The answers by Spacedman and Josh are really great, but I'd like to share two other alternatives which are relatively fast and simple.

    library(data.table)
    library(spatialEco)
    library(raster)
    library(rgdal)
    

    using a data.table approach:

    # get centroids of raster data
      data_points <- rasterToPoints(dat, spatial=TRUE)
    
    # intersect with polygons
      grid_centroids <- point.in.poly(data_points, polys)
    
    # calculate weighted centroids
      grid_centroids <- as.data.frame(grid_centroids)
      w.centroids <- setDT(grid_centroids)[, lapply(.SD, weighted.mean, w=layer), by=POLYID, .SDcols=c('x','y')]
    

    using wt.centroid{spatialEco} :

      # get a list of the ids from each polygon
        poly_ids <- unique(grid_centroids@data$POLYID)
    
      # use lapply to calculate the weighted centroids of each individual polygon
        w.centroids.list <- lapply(poly_ids, function(i){wt.centroid( subset(grid_centroids, grid_centroids@data$POLYID ==i)
                                                                      , 'layer', sp = TRUE)} )
    

提交回复
热议问题