R SF:转换sf geometry的格式

R SF: Transforming the format of sf geometry

我不知道这是一个错误,还是我在使用 sf 时太天真了,所以我在这里提出这个问题。我刚刚使用 st_sample 并为一些多边形生成了一些随机点,生成的几何列的格式类似于:

c(lon = 149096.638762965, lat = 175644.870597937)

然而,在我从 shapefile 生成的正常 sf 数据框中,几何图形看起来像这样:

c(151510.88605718, 177463.801340721)

我想知道这样的格式是否可以互换?如果我想将 st_sample 几何点与我的 shapefile 绑定,我可以像对大多数其他列那样使用 rbind 吗?

非常感谢您的提前帮助!

维度命名这一事实在绑定中不是问题。

绑定真实点和采样点时,您必须确定两件事:

  • 两个对象的 CRS 必须相同(否则会出现几何问题)
  • 两个对象的列名必须相同(否则会出现一般数据框问题);请注意,sf::st_sample() 的几何列默认名为“x”,这不是很友好 - 您可能希望将其更改为类似“几何”的名称。为此考虑 dplyr::select()

为了说明这一点,考虑这段代码:

library(sf)
library(dplyr)

# NC counties - a shapefile shipped with the sf package
counties <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = T) 

# three semi-random cities in NC
cities <- data.frame(name = c("Raleigh", "Greensboro", "Wilmington"),
                     x = c(-78.633333, -79.819444, -77.912222),
                     y = c(35.766667, 36.08, 34.223333)) %>% 
  st_as_sf(coords = c("x", "y"), crs = 4326)

# three fully random points in NC
points <- counties %>% 
  filter(NAME == "Mecklenburg") %>%  # as in Charlotte of Mecklenburg-Strelitz
  st_transform(st_crs(cities)) %>%   # to put on the same page as cities
  st_sample(3) %>% 
  st_as_sf() %>% 
  mutate(name = "some random place nearby Charlotte, NC")

# a quick check
plot(st_geometry(counties)) # bacground
plot(st_geometry(cities), pch = 4, col = "red", add = T)
plot(st_geometry(points), pch = 4, col = "blue", add = T)

# binding - note the rename of x column to geometry
final_bind <- cities %>% 
  rbind(select(points, name, geometry = x)) # note the rename in select!

str(final_bind)
# Classes ‘sf’ and 'data.frame':    6 obs. of  2 variables:
#  $ name    : chr  "Raleigh" "Greensboro" "Wilmington" "some random place nearby Charlotte, NC" ...
#  $ geometry:sfc_POINT of length 6; first list element:  'XY' num  -78.6 35.8
#  - attr(*, "sf_column")= chr "geometry"
#  - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA
#  ..- attr(*, "names")= chr "name"

# final overview - lo & behold! a single object!
mapview::mapview(final_bind)