tom
tom

Reputation: 725

How to read .csv polygon data with sf?

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.

Upvotes: 1

Views: 609

Answers (1)

Stewart Macdonald
Stewart Macdonald

Reputation: 2132

Here's something to get you started.

# Load packages
library('sf')
library('stringr')

# longitude latitude altitude accuracy;
v <- 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))

# Function to take the string, split it up, and turn it into a polygon
mkshp <- function(x) {
    
    x <- str_trim(x)
    
    y <- unlist(strsplit(x, split=' '))
    
    # Reshape it to a matrix
    m <- matrix(as.numeric(y), ncol=4, byrow=TRUE)
    
    # Just want the first two columns - long, lat
    m <- m[, 1:2]
    
    
    # Need to reorder the matrix because the coords are not in order
    # This bit will need to be rewritten to accomodate your real data
    m <- m[c(1, 2, 4, 3), ]
    
    
    # Need to close it by adding the first row to the end
    m <- rbind(m, m[1, ])
    
    # Create a polygon object
    st_polygon(list(m))
    
}

# shps will be a list of polygons (one for each row in the data frame)
shps <- lapply(strsplit(v$shape, split=';'), mkshp)

# Set these polygons as the geometry column in our data frame
st_geometry(v) <- st_as_sfc(shps)

# Set a Coordinate Reference System if you wnat
# st_crs(v) <- ...

plot(v, axes=T)

enter image description here

Upvotes: 1

Related Questions