R条件距离测量

R conditional distance measurement

我正在尝试确定数据集中的距离,但前提是它们满足特定条件。我在这里看到了很多确定两点之间距离的例子,但不确定如何指定我想要的点。

数据集(标题为 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

为 size-one 个组输入了零,但如果您愿意,可以用 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)