Skip to content

Instantly share code, notes, and snippets.

@giacecco
Last active December 25, 2015 18:59
Show Gist options
  • Save giacecco/7024453 to your computer and use it in GitHub Desktop.
Save giacecco/7024453 to your computer and use it in GitHub Desktop.
Problem: I would like to write a vectorised version of 'findClosestOutputArea' below, so that I could do something like: incidents$outputAreaGridId <- findClosestOutputAreaVectorised(incidents$davetazLongitude, incidents$davetazLatitude)$gridId 'spDistsN1' comes from package sp http://cran.r-project.org/web/packages/sp/sp.pdf and calculates the …
date time incidentGroup borough ward firstPumpTime firstPumpStation
1 2009-01-01 00:00:37 Special Service Wandsworth Battersea 319 Battersea
3 2009-01-01 00:03:00 Fire Enfield Edmonton 308 Edmonton
4 2009-01-01 00:04:27 Fire Hillingdon Hillingdon 210 Hillingdon
5 2009-01-01 00:05:39 Fire Islington Holloway 233 Holloway
6 2009-01-01 00:06:03 False Alarm Camden Kentish Town 172 Kentish Town
7 2009-01-01 00:12:31 Special Service Greenwich Lee Green 522 East Greenwich
latitude longitude davetazLatitude davetazLongitude
1 51.47548 -0.14733791 51.475 -0.1485
3 51.63247 -0.06724327 51.632 -0.0675
4 51.53378 -0.44635059 51.533 -0.4470
5 51.55132 -0.10963551 51.551 -0.1110
6 51.55079 -0.13273866 51.550 -0.1335
7 51.46174 0.03063764 51.461 0.0300
gridId longitudeCentre latitudeCentre davetazArea
1 1122313323 -0.504 51.11170 926.4539
2 1122313324 -0.552 51.11170 926.4539
3 1122313331 -0.552 51.14050 925.8764
4 1122313332 -0.504 51.14050 925.8764
5 1122313333 -0.504 51.16935 928.5105
6 1122313334 -0.552 51.16935 812.0626
findClosestOutputArea <- function (incident) {
distances <- spDistsN1(data.matrix(outputAreas[, c('longitudeCentre', 'latitudeCentre')]), matrix(c(incident$davetazLongitude, incident$davetazLatitude), nrow = 1, ncol = 2, byrow = TRUE), longlat = TRUE)
outputAreas[match(min(distances), distances), ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment