如何使用sf::st_centroid计算多边形的重心?

25

我正在使用新的"sf"包在R中处理一些巴西人口普查数据。我可以成功导入数据,但是当我尝试创建原始多边形的质心时出现错误。

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"列质心的新几何列,但出现了错误:

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

我该如何解决这个问题?


4
这不是一个错误,而是一个警告。这些数值已经被创建了。 - Sven Hohenstein
1个回答

29
所有支撑sf的GEOS函数都需要投影坐标才能正常工作,因此您应该在适当投影的数据上运行st_centroid。我不太了解巴西可用的CRS,但EPSG:29101似乎可以正常工作:
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)

第二个plot()调用给了我“不支持绘制列表列”的错误。我也无法在该列中获得任何质心,不确定答案是否过时(他们经常更改sf包)。 - CoderGuy123
1
嗨@Deleet,看起来现在必须在绘图之前激活次要几何列,例如plot(st_set_geometry(d, 'centroids')[, 0], add = T, col = 'red', pch = 19)。我正在Windows环境中使用sf 0.8-0。 - obrl_soil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接