gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:15:37 24 4
gpt4 key购买 nike

我有一组来自不同个体的位置点:

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对象,所以任何一种方法都可以。我喜欢管道解决方案,但我会尽我所能。谢谢!

最佳答案

这是比尔在评论中提到的:

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)


关于r - 计算两个不同分组数据框中位置点之间的最大距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63236651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com