TransWikia.com

How to read .csv polygon data with sf?

Geographic Information Systems Asked on April 2, 2021

I am trying to read a .csv file where each row contains information about a polygon. The polygon geometry information is stored in a shape column such as 'longitude latitude altitude accuracy; ...'.

Here is a simplified example with a single square polygon:

structure(list(field = "parcel_a", shape = "5 50 0 0.5; 20 50 0 0.5; 5 40 0 0.5; 20 40 0 0.5"), class = "data.frame", row.names = c(NA, 
-1L))

How can I read this data format with sf in R? I would also be interested to know where does this format come from.

One Answer

Its close to being like a part of a WKT format string.

You have:

"5 50 0 0.5; 20 50 0 0.5; 5 40 0 0.5; 20 40 0 0.5"

and the relevant WKT string would probably be:

"POLYGON ((5 50 0 0.5, 20 50 0 0.5, 5 40 0 0.5, 20 40 0 0.5))"

To convert to that and make sf objects...

  1. Replace all semicolons with commas:
gsub(";",",",S$shape)
## [1] "5 50 0 0.5, 20 50 0 0.5, 5 40 0 0.5, 20 40 0 0.5"
  1. Paste on the word "POLYGON" and some parentheses:
paste0("POLYGON ((",gsub(";",",",S$shape),"))")
## [1] "POLYGON ((5 50 0 0.5, 20 50 0 0.5, 5 40 0 0.5, 20 40 0 0.5))"
  1. make into a data frame and use st_as_sf:
> st_as_sf(data.frame(g=paste0("POLYGON ((",gsub(";",",",S$shape),"))")),wkt="g")
## Simple feature collection with 1 feature and 0 fields
## geometry type:  POLYGON
## dimension:      XYZM
## bbox:           xmin: 5 ymin: 40 xmax: 20 ymax: 50
## z_range:        zmin: 0 zmax: 0
## m_range:        mmin: 0.5 mmax: 0.5
## CRS:            NA
##                                g
## 1 POLYGON ZM ((5 50 0 0.5, 20...

Note this is a "POLYGON ZM" - you've got four coordinates in each part and this is treating the data as three dimensional with an "M" measurement.

and then at this point you realise that WKT needs the first point repeating in order to close the POLYGON. Oops.

So instead create it as a LINESTRING and coerce to POLYGON.

SQ = st_as_sf(
   data.frame(
    geom=paste0("LINESTRING (",gsub(";",",",S$shape),")")
   ),
   wkt="geom")

SQ = st_cast(SQ,"POLYGON")
plot(st_zm(SQ))

enter image description here

That's not a valid Simple Features polygon though because of the self-intersection...

Correct answer by Spacedman on April 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP