Calculating maximum distance between location points in two different grouped data frames

Viewed 109

I have a set of location points from different individuals:

locations <- data.frame(
  id=c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'),
  xcoord=c(1, 8, 5, 22, 26, 24, 37, 35, 39),
  ycoord=c(3, 2, 9, 25, 23, 28, 31, 35, 33)
)

Each individual also has a single, central location.

center <- data.frame(
  id=c('A', 'B', 'C'),
  xcoord=c(5, 24, 36),
  ycoord=c(4, 23, 34)
)

I need to know the distance of the furthest location point from the central point for each individual. I've tried working with distm() and st_distance() but I've been having trouble with the grouping aspect. For example,

distm(cbind(locations$xcoord, locations$ycoord), cbind(center$xcoord, center$ycoord))

calculates distances just fine but doesn't differentiate between individuals (and is also kind of clunky). I have a dozen individuals with hundreds of points each, so keeping track of IDs is important. It's easy for me to convert between data.frame and a sf objects, so either approach is fine. I'd love a piped solution but I'll take what I can get. Thanks!

1 Answers

Here is what Bill mentioned in the comments:

library(dplyr)
# modify names for the center dataframe
names(center)[2:3] <- paste0("center", names(center)[2:3])

# left join
locations.center <- left_join(locations, center)

# calculate the distance for each one
locations.center <- mutate(locations.center, dist=sqrt((xcoord-centerxcoord)^2 + (ycoord-centerycoord)^2))

    
# now if you only care about the max distance for each id:  
# (note this step can be combined with the previous step)         
locations.center <- group_by(locations.center, id)  %>% arrange(desc(dist)) %>% slice(1)  

    
Related