Advertisement
Guest User

Untitled

a guest
Jul 1st, 2015
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1.  
  2. to.radians<-function(degrees){
  3. degrees * pi / 180
  4. }
  5.  
  6.  
  7. #-----------------------------------------------------------------------------
  8. # Vectorised havershine (lat1, long1) is a single point
  9. # lats and longs vectors of other places
  10. # returns a vector of distances from (lat1, long1) to each of the other places specified
  11. #-----------------------------------------------------------------------------
  12. vhaversine <- function(lat1, long1, lats, longs) {
  13. radius <- 6378 # radius of Earth in kilometers
  14. term1 <- sin((lats - lat1)/2) ^ 2
  15. term2 <- cos(lat1) * cos(lats) * sin((longs - long1)/2) ^ 2
  16. the.terms <- term1 + term2
  17. delta.sigma <- 2 * atan2(sqrt(the.terms), sqrt(1-the.terms))
  18. distance <- radius * delta.sigma
  19. return(distance)
  20. }
  21.  
  22. #-----------------------------------------------------------------------------
  23. # My version calling vectorised havershine
  24. #-----------------------------------------------------------------------------
  25. just.R.mike.vectorised <- function(dframe){
  26. numrows <- nrow(dframe)
  27.  
  28. lats <- to.radians(dframe$x)
  29. longs <- to.radians(dframe$y)
  30.  
  31. acc <- 0
  32. for (ii in 1:(numrows-1)) {
  33. acc <- acc + sum(vhaversine(lats[ii], longs[ii], lats[(ii+1):numrows], longs[(ii+1):numrows]))
  34. }
  35.  
  36. acc / (numrows*(numrows-1)/2)
  37. }
  38.  
  39.  
  40. #-----------------------------------------------------------------------------
  41. # Create data and do timings of the two methods
  42. #-----------------------------------------------------------------------------
  43. df <- read.csv("optim/Airport_Codes_mapped_to_Latitude_Longitude_in_the_United_States.csv", as.is=TRUE)
  44. colnames(df) <- c('locationID', 'x', 'y')
  45.  
  46.  
  47. system.time({print(just.R.mike.vectorised(df)) })
  48.  
  49. #> [1] 1869.744
  50. #> user system elapsed
  51. #> 10.021 3.000 13.036
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement