简体   繁体   English

计算两个不同分组数据框中位置点之间的最大距离

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

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.我试过使用distm()st_distance()但我在分组方面遇到了麻烦。 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.我有十几个人,每个人都有数百分,所以跟踪 ID 很重要。 It's easy for me to convert between data.frame and a sf objects, so either approach is fine.我很容易在data.framesf对象之间进行转换,所以这两种方法都可以。 I'd love a piped solution but I'll take what I can get.我喜欢管道解决方案,但我会尽我所能。 Thanks!谢谢!

Here is what Bill mentioned in the comments:以下是 Bill 在评论中提到的内容:

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)  

    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM