How to calculate centroid of polygon using sf::st_centroid?

狂风中的少年 提交于 2020-07-05 06:57:51

问题


I am trying to manipulate some Brazilian Census data in R using the new "sf" package. I am able to import the data, but I get an error when I try to create the centroids of the original polygons

library(sf)

#Donwload data  
filepath <- 'ftp://geoftp.ibge.gov.br/organizacao_do_territorio/malhas_territoriais/malhas_de_setores_censitarios__divisoes_intramunicipais/censo_2010/setores_censitarios_shp/ac/ac_setores_censitarios.zip'
download.file(filepath,'ac_setores_censitarios.zip')
unzip('ac_setores_censitarios.zip')
d <- st_read('12SEE250GC_SIR.shp',stringsAsFactors = F) 

Now I try to create a new geometry column containing the centroid of column "geometry", but get an error:

d$centroid <- st_centroid(d$geometry)
Warning message:
In st_centroid.sfc(d$geometry) :
  st_centroid does not give correct centroids for longitude/latitude data

How can I solve this?


回答1:


All the GEOS functions underlying sf need projected coordinates to work properly, so you should run st_centroid on appropriately projected data. I don't know much about Brazil's available CRS's, but EPSG:29101 appears to work fine:

library(tidyverse)

d$centroids <- st_transform(d, 29101) %>% 
  st_centroid() %>% 
  # this is the crs from d, which has no EPSG code:
  st_transform(., '+proj=longlat +ellps=GRS80 +no_defs') %>%
  # since you want the centroids in a second geometry col:
  st_geometry()

# check with
plot(st_geometry(d))
plot(d[, 'centroids'], add = T, col = 'red', pch = 19)


来源:https://stackoverflow.com/questions/46176660/how-to-calculate-centroid-of-polygon-using-sfst-centroid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!