0

So I have a formula for calculating the distance between two locations,however I want to have a second function that uses this one. The second function would get a list of lat, long values with corresponding numbers 1,2,3,etc.Then for for each point on the list run the GPSDist on all the other lat long data in that column. find the set that has the smallest distance (d) value, and say what number that lat long corresponds to.

GPSDist <- function(lon1,lat1,lon2,lat2,u){
  if (u=="k"){R<-6373}
  if (u=="m"){R<-6378137}
  if (u=="M"){R<-3961}
  if (u=="k"){print("unit = kilometers")}
  if (u=="m"){print("unit = meters")}
  if (u=="M"){print("unit = miles")} 

 radians <- 0.0174532925
 lon1 <- lon1* radians
 lat1 <- lat1* radians
 lon2 <- lon2* radians
 lat2 <- lat2* radians
 dlon <- lon2-lon1
 dlat <- lat2-lat1
 a <- ((sin((dlat)/2))^2) + cos(lat1) * cos(lat2) * ((sin((dlon)/2))^2)
 c <- 2 * atan2(sqrt(a), sqrt(1-a)) 
 d = c*R

 return(d)
}

for clarity I would like use that function (GPSDist) on each point on say there is a data set 1 to 5; use point 1 against points 2,3,4,5. find smallest list it by its respective number. use point 2 compare to points 1,3,4,5 etc.

RyanMe321
  • 177
  • 3
  • 11
  • What is your question? Your function `GPSDist()` appears to be working as you planned. – Tim Biegeleisen May 11 '15 at 01:51
  • I think RyanMe321 wanted to know how to find the smallest distance among points, provided they were all in a data frame or matrix. – Max Candocia May 11 '15 at 02:06
  • I would like use that function (GPSDist) on each point on say there is a data set 1 to 5; use point 1 against points 2,3,4,5. find smallest list it by its respective number. use point 2 compare to points 1,3,4,5 etc. – RyanMe321 May 11 '15 at 02:17

1 Answers1

0

First, it always helps if you define an example data set. So, here is one for you:

point1 <- c(1,3)
point2 <- c(4,5)
point3 <- c(7,9)
point4 <- c(11,13)
point5 <- c(89,5)

pointList <- list(point1, point2, point3, point4, point5)

Next, this can probably be solved with nested for loops.

GPDistOthers <- function(inputList, u) {
  output <- list()
  for (i in 1:length(inputList)) {
    currentList <- list()
    for (j in 1:length(inputList)) {
      if (i != j) {
        currentList <- c(currentList, GPSDist(inputList[[i]][1], inputList[[i]][2], inputList[[j]][1], inputList[[j]][2], u))
      }
    }
    output[[length(output)+1]] <- currentList
  }
  return(output)
}

If you are trying to run this many times, you will make your code run much faster by implementing this using lapply as described here: Access lapply index names inside FUN

Community
  • 1
  • 1
waternova
  • 1,472
  • 3
  • 16
  • 22