0

I have a data frame that boiled down looks like:

dat <- data.frame(longitude = c(80.15998, 72.89125, 77.65032, 77.60599), 
                latitude = c(12.90524, 19.08120, 12.97238, 12.90927),
                site = c("a", "b", "c", "d"), 
                source = c("K", "K",  "P", "P"))

I would like to figure out how to find distances between each possible pairing of the sites (so pairing a-b, a-c, a-d, b-c, etc.). So the end result might look like

        a    b    c    d
 a      
 b
 c
 d

with the distances filled in obviously.

I know for distance that I should be using library(geosphere) and distm() or distHaversine() ?

Any help is appreciated!

SymbolixAU
  • 25,502
  • 4
  • 67
  • 139
Ally D
  • 165
  • 11
  • Did you check [this](https://stackoverflow.com/questions/31668163/geographic-geospatial-distance-between-2-lists-of-lat-lon-points-coordinates) ? – Ronak Shah Feb 16 '18 at 05:35
  • Ya I looked at that one, but to be honest, I wasn't sure how to manipulate it to fit my needs, since they have theirs on 2 lists. I felt like this was the part I needed `list1 <- list1 %>% mutate(near_dist = mat2[matrix(c(1:10, max.col(-mat2)), ncol = 2)])` from theirs where they create mat2 with `mat2 <- distm(list1[,c('longitude','latitude')], list2a[,c('longitude','latitude')], fun=distVincentyEllipsoid)`. Do you think I need to create to lists to recreate their method? – Ally D Feb 16 '18 at 05:43
  • 1
    I think just `distm(dat[, c(1, 2)], dat[, c(1, 2)])` will give you the matrix that you need? – Ronak Shah Feb 16 '18 at 05:54
  • oh, well that worked well didn't it? Is there any way for it to take the site names along with it so that they are labelled as the column names and row names? – Ally D Feb 16 '18 at 05:58
  • 1
    I am not sure if you can do it from within the function itself but you can do it after `df <- distm(dat[c(1, 2)], dat[c(1, 2)])` using `rownames(df) <- dat$site` and `colnames(df) <- dat$site`. – Ronak Shah Feb 16 '18 at 06:09

0 Answers0