gis - How to calculate distance matrix using gDistance in R? -
i'd calculate distance polygons. calculate methode, use hausdorff distance. have calculate 2 polygon only. how calculate polygons? need please. source code calculate 2 polygon
library(maptools)
library(rgdal)
shape <- readshapepoly("clipjawa.shp") #load file .shp
pemalang <- shape[1,1] #save coordinates polygon 1 variable pemalang
tegal <- shape[2,1] #save coordinates polygon 2 variable tegal
distance <- gdistance(pemalang,tegal,hausdorff=true)
there several ways approach this, perhaps simplest identify combinations (pairs) of indices of polygons, , apply gdistance
each of these combinations.
here's example, calculating hausdorff distances pairs of countries in africa, using wrdl_simpl
dataset included maptools
.
# load , project data library(maptools) data(wrld_simpl) africa <- sptransform(subset(wrld_simpl, region==2), crs('+proj=eqc +lon_0=20.390625')) # calculate pairs of polygons combns <- t(combn(length(africa), 2)) # split spdf list of spdfs africa.split <- split(africa, seq_len(length(africa))) # each row of combns, calculate haus. dist. relevant pair of # polygons dists <- apply(combns, 1, function(x) gdistance(africa.split[[x[1]]], africa.split[[x[2]]], hausdorff=true))
you can bind these results matrix of combinations convenience:
hdists <- cbind.data.frame(from=as.character(africa$name[combns[, 1]]), to=as.character(africa$name[combns[, 2]]), d=dists) head(hdists) # d # 1 algeria angola 4733071 # 2 algeria benin 2807129 # 3 algeria congo 4056594 # 4 algeria democratic republic of congo 4532625 # 5 algeria burundi 5464898 # 6 algeria cameroon 3071739
an alternative approach use outer
, should less efficient since calculates distances twice (but directly return distance matrix, might desirable).
outer(africa.split, africa.split, fun = vectorize(function(x, y) gdistance(x, y, hausdorff=true)))
(updated example)
Comments
Post a Comment