0

I'm trying to measure the difference between locations, without repetition.

I have a dataframe with citynames and lon + lat columns. The distance should be measured between city1 and city2, city1 and city3, etc. Until city n-1 and city n.

My tries have been varied, but the latest was:

    i <- 1
    j <- 2
    while (i < 51){
      while (j < 50){
        setDT(df)
        df[, distance_hav := distHaversine(matrix(c(df$lon[i]
                                , df$lat[i]
                                , ncol = 2)
                                , matrix(c(df$lon[j]
                                , df$lat[j]
                                , ncol = 2))]

        j <- j + 1          
        }
      i <- i + 1 
      }

Any help is much appreciated.

Frank_C
  • 23
  • 3
  • You're totally right, I forgot to add counters. – Frank_C Jun 04 '17 at 12:23
  • Your `df$distance_hav` column is being overwritten on each iteration, so you'd only get the last iteration's result returned. – rosscova Jun 04 '17 at 12:24
  • You need to create a distance matrix. [Here you'll find an example on how to do that](https://stackoverflow.com/a/31668415/2204410). – Jaap Jun 04 '17 at 12:34
  • Many thanks! That is a duplicate indeed, but to a certain degree. I have a matrix that is in a sense 'double', and I'd just need a list of distances, having only one instance. As having 3 locations, it would be: distance_Location1-Location2, distance_Location1-Location3, distance_Location2-Location3. – Frank_C Jun 04 '17 at 14:17

0 Answers0