gpt4 book ai didi

r - SF : Write Lat/Long from geometry into separate column and keep ID column

转载 作者:行者123 更新时间:2023-12-02 12:01:38 26 4
gpt4 key购买 nike

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

# 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)

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

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

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

数据帧的输出是:

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() 的解决方案

library(tidyverse)

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

separated_coord

关于r - SF : Write Lat/Long from geometry into separate column and keep ID column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com