sf:将几何中的纬度/经度写入单独的列并保留 ID 列 [英] sf: Write Lat/Long from geometry into separate column and keep ID column

查看:50
本文介绍了sf:将几何中的纬度/经度写入单独的列并保留 ID 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自 shapefile 的多边形 ID 及其几何列中的中心点的 df:

I have a df with polygon ID's from a shapefile and their centre-points in a geometry column:

# A tibble: 3 x 2
     ID     geometry
  <dbl> <POINT [°]>
1     1 (117.2 31.8)
2     2 (116.4 40.1)
3     4   (117.9 26)

我想将纬度/经度值放入单独的列中,所以我这样做:

I want to put the latitude/longitude values into separate columns, so I do:

library(sf)
centres<- as.data.frame(st_coordinates(df))

这个新的中心"数据框具有经纬度值,但缺少 ID 列.我该如何保留它,或者是否有另一种方法可以将经纬度值从几何列中提取到单独的列中,同时将 ID 保持在相同的 df 中?

This new 'centres' dataframe has the lat&long values, but misses the ID column. How can I preserve it, or is there another way to get the lat&long values into separate columns from the geometry column whilst keeping the ID in the same df?

数据框的 dput 是:

dput for the dataframe is:

df <- structure(list(ID = c(1, 2, 4), 
      geometry = structure(list(structure(c(117.2, 31.8), 
      class = c("XY", "POINT", "sfg")), structure(c(116.4, 40.1), 
      class = c("XY", "POINT", "sfg")), structure(c(117.9, 26.0), 
      class = c("XY", "POINT", "sfg"))), class = c("sfc_POINT", "sfc"), 
      precision = 0, bbox = structure(c(xmin = 116.4, ymin = 26.0, xmax = 117.9, ymax = 40.1), 
      class = "bbox"), crs = structure(list(epsg = 4326L, 
      proj4string = "+proj=longlat +datum=WGS84 +no_defs"), class = "crs"), n_empty = 0L)), 
      row.names = c(NA, -3L), class = c("sf", "tbl_df", "tbl", "data.frame"), 
      sf_column = "geometry", agr = structure(c(ID = NA_integer_), 
      class = "factor", .Label = c("constant", "aggregate", "identity")))

推荐答案

使用 unlist + map() 的解决方案

Solution using unlist + map()

library(tidyverse)

separated_coord <- df %>%
    mutate(lat = unlist(map(df$geometry,1)),
           long = unlist(map(df$geometry,2)))

separated_coord

这篇关于sf:将几何中的纬度/经度写入单独的列并保留 ID 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆