在 R 和 sf 中,如何更新所选要素的坐标?

3

我遇到了一个看似简单的问题。我想手动纠正一些点的地理编码结果,比如说需要更新“Dare”位置的质心:

library(sf)     
nc <- st_centroid(st_read(system.file("shape/nc.shp", package = "sf")))
st_coordinates(filter(nc, NAME== "Dare"))

我该如何更改原始值

          X        Y
1 -75.80982 35.73548

想转行吗?

我预计的是类似这样的东西

st_coordinates(filter(nc, NAME== "Dare")) <- matrix(c(-73, 33), nrow = 1)

或者
nc %>% 
  mutate(geometry = ifelse(place_full_name == "Dare", 
                           yes = st_set_geometry(c(-73, 33)), 
                           no = geometry))

想要完成该工作,但两种解决方案都会产生错误。


关于这个话题,Twitter 上有一些讨论 https://twitter.com/RPanczak/status/1082527408736034816 - radek
2个回答

4

请使用st_geometry<-命令。

获取原始几何信息(仅用于检查):

st_geometry(nc[nc$NAME == "Dare", ])
# Geometry set for 1 feature 
# geometry type:  POINT
# dimension:      XY
# bbox:           xmin: -75.80982 ymin: 35.73548 xmax: -75.80982 ymax: 35.73548
# epsg (SRID):    4267
# proj4string:    +proj=longlat +datum=NAD27 +no_defs
# POINT (-75.80982 35.73548)

使用st_geometry<-替换选定几何图形。替换值需要是一个简单的要素几何,因此使用st_sfc(st_point(...

st_geometry(nc[nc$NAME == "Dare", ]) <-  st_sfc(st_point(c(-80, 40)))

# check again
st_geometry(nc[nc$NAME == "Dare", ])
# Geometry set for 1 feature 
# geometry type:  POINT
# dimension:      XY
# bbox:           xmin: -80 ymin: 40 xmax: -80 ymax: 40
# epsg (SRID):    4267
# proj4string:    +proj=longlat +datum=NAD27 +no_defs
# POINT (-80 40)

注意:

由@radek分享的Twitter讨论中,sf包的作者@Edzer Pebesma评论说原始几何图形的边界框没有更新。

原始边界框:

st_bbox(nc)
#      xmin      ymin      xmax      ymax 
# -84.05976  34.07663 -75.80982  36.49101

用超出原始边界框的坐标替换所选几何体,这里的x小于xminy大于ymax:

st_geometry(nc[nc$NAME == "Dare", ]) <-  st_sfc(st_point(c(-90, 40)))

对象的bbox未更新:
st_bbox(nc)
#      xmin      ymin      xmax      ymax 
# -84.05976  34.07663 -75.80982  36.49101  

1
您可以像@Henrik的答案中一样使用st_geometry<-,但是需要替换整个几何图形以更新边界框。
st_geometry(nc) <- st_sfc(
    ifelse(nc$NAME == "Dare", st_sfc(st_point(c(-90, 40))), nc$geometry),
    crs = st_crs(nc$geometry))

请注意,对象的bbox现在已更新:
st_bbox(nc)
#      xmin      ymin      xmax      ymax 
# -90.00000  34.07663 -76.02750  40.00000

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