计算两个不同分组数据框中位置点之间的最大距离
Calculating maximum distance between location points in two different grouped data frames
我有一组来自不同个体的定位点:
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)
)
每个人也有一个中心位置。
center <- data.frame(
id=c('A', 'B', 'C'),
xcoord=c(5, 24, 36),
ycoord=c(4, 23, 34)
)
我需要知道每个人的中心点 的最远位置点的距离。 我试过使用 distm()
和 st_distance()
但我在分组方面遇到了麻烦。例如,
distm(cbind(locations$xcoord, locations$ycoord), cbind(center$xcoord, center$ycoord))
可以很好地计算距离,但不能区分个体(而且有点笨拙)。我有十几个人,每个人都有数百分,所以跟踪 ID 很重要。我很容易在 data.frame
和 sf
对象之间进行转换,所以这两种方法都可以。我喜欢管道解决方案,但我会尽我所能。谢谢!
以下是 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)
我有一组来自不同个体的定位点:
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)
)
每个人也有一个中心位置。
center <- data.frame(
id=c('A', 'B', 'C'),
xcoord=c(5, 24, 36),
ycoord=c(4, 23, 34)
)
我需要知道每个人的中心点 的最远位置点的距离。 我试过使用 distm()
和 st_distance()
但我在分组方面遇到了麻烦。例如,
distm(cbind(locations$xcoord, locations$ycoord), cbind(center$xcoord, center$ycoord))
可以很好地计算距离,但不能区分个体(而且有点笨拙)。我有十几个人,每个人都有数百分,所以跟踪 ID 很重要。我很容易在 data.frame
和 sf
对象之间进行转换,所以这两种方法都可以。我喜欢管道解决方案,但我会尽我所能。谢谢!
以下是 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)