将CSV转换为r中的SHP,其中几何为单列



我有一个csv文件,其中包含单个列中的点几何信息。是否有一种直接的方法来转换从csv到空间数据文件在r给定的几何列的格式(我可以在QGIS中做到这一点,或者可以将列拼接成x和y,但我很好奇是否有更好的方法来做到这一点)。

下面是一个数据的示例:

name <- c("A", "B", "C")
geom <- c("POINT (45.095914704767 -93.266719775361)",
"POINT (45.095220489232 -93.254896591796)",
"POINT (45.079643666 -93.257941333)")
dat <- data.frame(name, geom)
dat

你的几何图形的格式" POINT (45, -93)"是众所周知的知名文本,它是几何图形的标准表示。

{sf}库可以直接读取已知文本(WKT)

library(sf)
sf::st_as_sf(x = dat, wkt = "geom")
# Simple feature collection with 3 features and 1 field
# Geometry type: POINT
# Dimension:     XY
# Bounding box:  xmin: 45.07964 ymin: -93.26672 xmax: 45.09591 ymax: -93.2549
# CRS:           NA
# name                       geom
# 1    A POINT (45.09591 -93.26672)
# 2    B  POINT (45.09522 -93.2549)
# 3    C POINT (45.07964 -93.25794)

如果您的几何列实际上被格式化为字符串,您可以使用dplyr剥离多余的文本,然后使用sf包将坐标转换为点列:

library(magrittr)
dat %>%
dplyr::mutate(
# replace text and parenthesis
geom = stringr::str_replace(geom, 'POINT \(', ''),
geom = stringr::str_replace(geom, '\)', '')
) %>%
# separate into lat and lon columns
tidyr::separate(geom, into=c('lon', 'lat'), sep=' ') %>%
# convert to sf point object 
# (assuming this is in WGS84, but you can specify any CRS here)
sf::st_as_sf(coords = c('lat', 'lon'), crs=4326)

如果你可以将csv文件保存为。geojson或。shp文件,你可以使用sf::read_sf('path/to/your/data.shp')函数将其读入R。

With base regex (and sf):

library(sf)
dat$y <- gsub(pattern = ".*\((-?[0-9.]+).*", replacement= "\1", dat$geom)
dat$x <- gsub(pattern = ".*\s(-?[0-9.]+).*", replacement= "\1", dat$geom)
dat_sf <- st_as_sf(dat, coords = c("y","x"))
st_write(dat_sf, "dat.shp")
Created on 2021-10-05 by the reprex package (v2.0.1)