问题描述
我试图确定数据集中的距离,但前提是它们满足特定条件。我在这里看到了很多确定两个点之间的距离的示例,但是不确定如何指定想要的点。
数据集(标题为event.df)如下:
X Y Tag Date
34.355 -7.662 151401 2015-09-22
34.546 -7.016 151401 2015-09-22
34.425 -6.987 151401 2015-10-20
34.554 -7.803 151402 2015-10-22
34.555 -7.803 151402 2015-10-22
34.554 -7.804 151402 2015-10-22
我想说的是,如果标签ID相同,并且日期相同,则计算与这些点的距离(可能大于2)。
解决方法
与添加所有距离或随机距离相比,添加具有最大距离的单列实际上要容易得多。
以下是使用dplyr
进行分组的方法:
library(dplyr)
# write a function to find the maximum distance for each point in a group
find_max_dist = function(x,y) {
cbind(x,y) %>% dist %>% as.matrix %>% apply(1,max)
}
# use dplyr to run the function by group and put the result in a column
event.df %>%
group_by(Tag,Date) %>%
mutate(max_dist_within_group = find_max_dist(X,Y))
# # A tibble: 6 x 5
# # Groups: Tag,Date [3]
# X Y Tag Date max_dist_within_group
# <dbl> <dbl> <int> <chr> <dbl>
# 1 34.4 -7.66 151401 2015-09-22 0.674
# 2 34.5 -7.02 151401 2015-09-22 0.674
# 3 34.4 -6.99 151401 2015-10-20 0
# 4 34.6 -7.80 151402 2015-10-22 0.001
# 5 34.6 -7.80 151402 2015-10-22 0.00141
# 6 34.6 -7.80 151402 2015-10-22 0.00141
零号组中置零,但是您可以根据需要用NA
替换。
使用此数据:
event.df = read.table(text = " X Y Tag Date
34.355 -7.662 151401 2015-09-22
34.546 -7.016 151401 2015-09-22
34.425 -6.987 151401 2015-10-20
34.554 -7.803 151402 2015-10-22
34.555 -7.803 151402 2015-10-22
34.554 -7.804 151402 2015-10-22",header = TRUE)