Adrienne
Adrienne

Reputation: 11

convert csv to shp in r where geometry is in single column

I have a csv file that contains the point geometry information in a single column. Is there a straight forward way to convert from csv to a spatial data file in r given the format of the geometry column (I could do this in QGIS or could splice the column into x and y, but I'm curious if there is a better way to do it).

Here is an example of what the data look like:

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

Upvotes: 1

Views: 1431

Answers (3)

SymbolixAU
SymbolixAU

Reputation: 26258

The format of your geometry, "POINT (45, -93)", is what's know as Well-Known Text, it's a standard representation of geomtries.

The {sf} library can read Well-Known Text (WKT) directly

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)

Upvotes: 2

Skaqqs
Skaqqs

Reputation: 4140

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)

Upvotes: 0

ColinB
ColinB

Reputation: 666

If your geometry column is actually formatted as a string, you could use dplyr to strip away the excess text and then use the sf package to convert the coordinates into a point column:

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)

If you are able to save your .csv as a .geojson or a .shp file, you can just read it into R with the sf::read_sf('path/to/your/data.shp') function.

Upvotes: 1

Related Questions