简化spatialLines对象并转换为igraph对象
假设我在R中有一个spatialLines(数据帧)对象,具有高度的地理细节。我想简化这个对象(减少创建对象所需的坐标点数量,减少一些细节是可以的),然后将其转换为igraph对象 每个坐标点都应该是图形中的一个节点。图形节点属性应包含地理坐标,边属性应包含节点之间的地理距离。边还应继承存储在SpatialLines对象的数据帧部分中的属性 以下是我迄今为止所做的工作:简化spatialLines对象并转换为igraph对象,r,gis,igraph,shapefile,R,Gis,Igraph,Shapefile,假设我在R中有一个spatialLines(数据帧)对象,具有高度的地理细节。我想简化这个对象(减少创建对象所需的坐标点数量,减少一些细节是可以的),然后将其转换为igraph对象 每个坐标点都应该是图形中的一个节点。图形节点属性应包含地理坐标,边属性应包含节点之间的地理距离。边还应继承存储在SpatialLines对象的数据帧部分中的属性 以下是我迄今为止所做的工作: readShapeFile <- function(path, filename, crs){ shapefil
readShapeFile <- function(path, filename, crs){
shapefile <- readOGR(path.expand(path), filename)
if(is.na(is.projected(shapefile))){
projection(shapefile) <- CRS(crs)
} else{
shapefile <- spTransform(shapefile, CRS(crs))
}
return(shapefile)
}
canal_shapefile <- readShapeFile(PATH, FILENAME, "+init=epsg:4326")
lines <- canal_shapefile
length(coordinates(lines)[[1]][[1]][, 1]) ### To indicate how 'complex' the object is.
lines <- gSimplify(lines, tol = .001)
length(coordinates(lines)[[1]][[1]][, 1])
nodes <- NULL
edges <- NULL
for(i in 1:length(coordinates(lines))){
nodes <- rbind(nodes, coordinates(lines)[[i]][[1]])
for (j in 2:length(coordinates(lines)[[i]][[1]][, 1])){
node1 <- coordinates(lines)[[i]][[1]][j - 1, ]
node2 <- coordinates(lines)[[i]][[1]][j, ]
dist <- distance(node1[2], node1[1], node2[2], node2[1])$distance
edges <- rbind(edges, c(node1, node2, dist))
}
}
colnames(edges) <- c("node1_long", "node1_lat", "node2_long", "node2_lat", "dist")
NODE1 <- match(sprintf("%s:%s", edges[, "node1_long"], edges[, "node1_lat"]),
sprintf("%s:%s", nodes[, 1], nodes[, 2]))
NODE2 <- match(sprintf("%s:%s", edges[, "node2_long"], edges[, "node2_lat"]),
sprintf("%s:%s", nodes[, 1], nodes[, 2]))
EDGES <- cbind(NODE1, NODE2, edges[, "dist"])
NODES <- cbind(1:length(nodes[, 1]), nodes)
g <- graph.data.frame(EDGES, FALSE, NODES)
readShapeFile在不深入了解spatialLines
对象的详细信息的情况下,您最可能的方法是使用参数顶点
而不是NULL
根据你的描述,可能是这样的:
g = graph.data.frame(edge_list_with_distances, FALSE, points_with_coordinates)
其中:
points\u with_坐标
是一个包含所有点及其属性的数据框(第一列是点名称或唯一id,它们在生成的图形中成为符号顶点名称)
edge\u list\u with\u distance
是一个包含这些点之间距离的数据框:前两列必须对应于points\u with\u distance
)中的顶点符号名称。请提供可复制的代码和数据,以供您迄今为止的尝试使用@Hack-R,我添加了数据源和部分解决方案。谢谢