R语言 将给定的多边形坐标对转换为sf对象

zbsbpyhn  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(102)

我将一个geoJSON对象加载到R中,并将jsonlite作为对象poly_shapepoly_shape有4列,其中一列称为geometry,包含坐标对中的多边形数据。例如,poly_shape$geometry的第一行看起来像这样:

[[1]]
           [,1]      [,2]
  [1,] 27.81674 -82.05954
  [2,] 27.81499 -82.05964
  [3,] 27.81498 -82.05872
  [4,] 27.81484 -82.05872
  [5,] 27.81492 -82.05889

如何将这个对象转换为sf对象,因为st_as_sf只返回

Error in st_sf(x, ..., agr = agr, sf_column_name = sf_column_name) : no simple features geometry column present
svmlkihl

svmlkihl1#

我最近写了一个小函数来做这件事。

library(tidyverse)
library(sf)
#> Linking to GEOS 3.10.2, GDAL 3.4.1, PROJ 7.2.1; sf_use_s2() is TRUE

# create data.frame
df <-
  tribble(
    ~ lat,     ~ long,
    27.81674, -82.05954,
    27.81499, -82.05964,
    27.81498, -82.05872,
    27.81484, -82.05872,
    27.81492, -82.05889
  )

# write function
fn_convert_to_polygon <- function(df){
  df %>% 
    as.matrix(ncol = 2) %>% 
    as.numeric() %>% 
    matrix(ncol = 2) %>% 
    st_linestring() %>% 
    st_cast('POLYGON') %>% 
    st_sfc()
}

# apply function
fn_convert_to_polygon(df) %>% 
  st_as_sf()
#> Simple feature collection with 1 feature and 0 fields
#> Geometry type: POLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 27.81484 ymin: -82.05964 xmax: 27.81674 ymax: -82.05872
#> CRS:           NA
#>                                x
#> 1 POLYGON ((27.81674 -82.0595...

创建于2023-10-10使用reprex v2.0.2

相关问题