问题描述
我正在尝试读取一个 .csv 文件,其中每一行都包含有关多边形的信息。多边形几何信息存储在 shape
列中,例如 'longitude latitude altitude accuracy; ...'
。
这是一个带有单个正方形多边形的简化示例:
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))
如何在 R 中使用 sf
读取这种数据格式?我也很想知道这种格式来自哪里。
解决方法
这里有一些东西可以帮助您入门。
# 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)