如何使用sf :: st_centroid计算多边形的质心? [英] How to calculate centroid of polygon using sf::st_centroid?
问题描述
我正在尝试使用新的"sf"软件包来处理R中的某些巴西人口普查数据.我可以导入数据,但是在尝试创建原始多边形的质心时会出现错误
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)
现在,我尝试创建一个新的几何列,其中包含列"geometry"的质心,但是会出现错误:
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
我该如何解决?
推荐答案
sf
下的所有GEOS函数都需要投影坐标才能正常工作,因此应在适当投影的数据上运行st_centroid
.我对巴西可用的CRS知之甚少,但EPSG:29101似乎运行良好:
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)
这篇关于如何使用sf :: st_centroid计算多边形的质心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!