将多边形shapefile导出为XY顶点对列表

时间:2019-10-17 18:20:45

标签: r sf

对于连续的多边形shapefile,我需要采用这种格式的多边形顶点坐标文件作为旧程序的输入:

polygon1name, AUTO
  -120.408750    34.591250
  -120.398313    34.591250
  -120.396250    34.593313
  -120.396250    34.593354
END
polygon2name, AUTO
  -120.423354    34.641250
  -120.423313    34.641250
  -120.421250    35.643313
  -120.421250    35.647521
END

从示例文件来看,旧程序看起来像是按逆时针绘制顺序对。这里以北卡罗莱纳州县为例。我希望在如何导出XY对以及包括, AUTOEND件方面都寻求帮助。

library(tidyverse) #for the %>% pipes and transmute()
library(sf) #for st_read()
library(rmapshaper) #for ms_simplify()

nc <- st_read(system.file("shape/nc.shp", package="sf")) %>%
      transmute(NAME, geometry) %>% #keeps just the county column for simplicity
      ms_simplify(keep = 0.01) #reduces the number of vertices for simplicity
plot(nc)

enter image description here

有什么想法吗?

谢谢。

1 个答案:

答案 0 :(得分:2)

不确定坐标的逆时针顺序,但这可以回答问题的输出格式部分。

#extract coordinates from sf
coord    <- st_coordinates(nc) %>% 
  as.data.frame() %>%
  group_by( L3 ) %>% 
  mutate(L4 = row_number() )

#extract data from sf
polygons <- st_drop_geometry(nc) %>% 
  mutate( NAME = as.character( NAME ) ) %>%
  rownames_to_column( var = "id" ) %>% 
  mutate( id = as.numeric(id) ) %>%
  #join coordinates
  left_join( coord, by = c("id" = "L3") )

#split polygons-dataframe to list
l <- split( polygons, f = polygons$id )

#extract text needed from each polygon
result <- lapply( l, function(x) {
  paste0 ( paste0( unique( x$NAME ), ", AUTO\n" ),
           paste0( "  ", x$X, "    ", x$Y, collapse = "\n" ),
           "\nEND" )
})

#unlist and write lines
writeLines( unlist(result) )

# Ashe, AUTO
# -81.4727554    36.2343559
# -81.7410736    36.3917847
# -81.6699982    36.5896492
# -81.3452988    36.5728645
# -81.2398911    36.3653641
# -81.4727554    36.2343559
# END
# Alleghany, AUTO
# -81.2398911    36.3653641
# -81.3452988    36.5728645
# -80.9034424    36.5652122
# -80.9563904    36.4037971
# -81.2398911    36.3653641
# END
# Surry, AUTO
# -80.4563446    36.2425575
# -80.874382    36.2338829

更新

对于逆时针部分:看一下check_ring_dir的{​​{1}}参数。

  

check_ring_dir
  逻辑如果为TRUE,则检查多边形环方向   并根据需要进行更正(从上方观察:外圈   逆时针方向,顺时针方向孔)