我有一个来自shapefile的带有多边形ID的df及其在几何列中的中心点:
# 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中?
数据框的dput是:
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")))
答案 0 :(得分:5)
st_geometry
可以与dplyr::mutate
一起使用:
library(magrittr) #for the pipe
df <- df %>%
dplyr::mutate(lat = sf::st_coordinates(.)[,1],
lon = sf::st_coordinates(.)[,2])
df
Simple feature collection with 3 features and 3 fields
geometry type: POINT
dimension: XY
bbox: xmin: 116.4 ymin: 26 xmax: 117.9 ymax: 40.1
CRS: EPSG:4326
# A tibble: 3 x 4
ID geometry lon lat
* <dbl> <POINT [°]> <dbl> <dbl>
1 1 (117.2 31.8) 117. 31.8
2 2 (116.4 40.1) 116. 40.1
3 4 (117.9 26) 118. 26
如果您不再关心geometry
,请使用df %>% sf::st_set_geometry(NULL)
答案 1 :(得分:0)
使用unlist + map()的解决方案
library(tidyverse)
separated_coord <- df %>%
mutate(lat = unlist(map(df$geometry,1)),
long = unlist(map(df$geometry,2)))
separated_coord
答案 2 :(得分:0)
一种可能的方法是将其取消列出。
setNames(data.frame(df[[1]],
matrix(unlist(df[2]), ncol=2, byrow=TRUE)),
c("ID", "lon", "lat"))
# ID lon lat
# 1 1 117.2 31.8
# 2 2 116.4 40.1
# 3 4 117.9 26.0
说明
使用str(df)
进行的数据结构检查显示,变量geometry
-的格式为list
,可能不方便。解决此问题的一种方法是unlist()
,将其转换为2列矩阵,然后将其与第一列重新组合。使用setNames()
,我们可以一步分配新的列名。