【问题标题】:R SF: Transforming the format of sf geometryR SF:转换 sf 几何的格式
【发布时间】:2021-09-08 17:17:07
【问题描述】:

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

c(lon = 149096.638762965, lat = 175644.870597937)

但是,在我从 shapefile 生成的普通 sf 数据框中,几何图形看起来像这样:

c(151510.88605718, 177463.801340721)

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

非常感谢您提前提供的帮助!

【问题讨论】:

    标签: r sf


    【解决方案1】:

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

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

    • 两个对象的 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)
    

    【讨论】:

    • 您好 Jindra,感谢您的回答。我想知道您是否在代码“..- attr(*, "names")= chr "name" 中做了任何事情,因为它没有正确显示在我的屏幕上?通过现有代码,final_bind 对象仍然由几何组成有两种不同的格式,但我想这不会影响未来的表现?
    • 我确实复制错了names属性!我的错!我已经编辑了答案,以便 str() 调用的打印输出看起来更清晰。如果您想摆脱命名坐标的最后痕迹,请考虑final_final &lt;- st_transform(final_bind, 4326);该对象已经在 EPSG:4326 中,但转换将对齐几何列的结构。
    • 这很清楚!谢谢 Jindra :) 祝你有美好的一天!
    猜你喜欢
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 2018-12-21
    • 2020-09-09
    • 1970-01-01
    • 2020-11-14
    • 2018-08-23
    • 2019-12-28
    相关资源
    最近更新 更多