【问题标题】:Keeping identifiers when calculating pointDistance between two data sets?在计算两个数据集之间的 pointDistance 时保留标识符?
【发布时间】:2014-08-20 23:34:39
【问题描述】:

万事如意,

我有两组点数据,一组包含 24 个位置,另一组包含约 16,000 个位置。我想计算从 24 个点到 16,000 个点的距离。使用 R raster 包中的 pointDistance() 很容易做到这一点,但我不知道正在比较哪些对。我想创建一个 data.frame,其中包含每次比较的位置名称,以便我可以将它与距离结合起来。

a <- data.frame('lon' = c(1,5,55,31), 'lat' = c(3,7,20,22), 'loc' = c('a', 'b', 'c', 'd'))
b <- data.frame('lon' = c(4,2,8,65), 'lat' = c(50,-90,20,32), 'loc' = c('e', 'f', 'g', 'h'))   
dist <- function(x, y){
 for( i in 1:length(a$lon)){
    my_vector <- vector(mode = "numeric", length = 0)
    d <- pointDistance(cbind(x[i,'lon'], x[i,'lat']), cbind(y$lon, y$lat), lonlat=TRUE)
    my_vector <- c(my_vector, d)
    }
    my_vector
 }

我的早晨很慢,无法弄清楚为什么上面的函数没有输出每个组合。它不会将 d 的每次迭代添加到 my_vector。

同时我想包括产生每个距离测量的位置的成对组合,例如:

  loc1   loc2   dist
     a      e     10
     a      f     16
     a      g     12
     a      h     19
     b      e     15
     b      f     17
     b      g     14
     b      h     13
     c      e     11
   etc    etc    etc

很抱歉打扰您,任何帮助将不胜感激。

提前致谢。

亚当

【问题讨论】:

    标签: r dataframe distance spatial


    【解决方案1】:

    您在每次迭代时都用零长度向量覆盖结果。在循环外声明你的变量:

    dist <- function(x, y){my_vector <- vector(mode = "numeric", length = 0)
     for( i in 1:length(a$lon)){
        d <- pointDistance(cbind(x[i,'lon'], x[i,'lat']), 
                           cbind(y$lon, y$lat), lonlat=TRUE)
        my_vector <- rbind(my_vector, d)
        }
        my_vector
     }
    > dist(a,b)
         [,1]     [,2]    [,3]    [,4]
    d 5239684 10352713 2039490 7401111
    d 4787647 10797991 1482960 6785859
    d 5571477 12245144 4899364 1666956
    d 3909092 12467783 2398381 3534050
    

    我认为rbind 在这种情况下比c() 是一个更好的“粘合剂”

    【讨论】:

    • 当然!这是其中一个早晨...谢谢您的帮助
    【解决方案2】:

    plyr假设“loc”的值是唯一的……

    fdist <- function(p1,p2) { pointDistance(cbind(a$lon[a$loc==p1], a$lat[a$loc==p1]),
                                         cbind(b$lon[b$loc==p2], b$lat[b$loc==p2]), lonlat=TRUE)}
    d <- ddply(expand.grid(a=a$loc,b=b$loc),.(a,b),mutate,dist=fdist(a,b))
    

    产生:

       a b      dist
    1  a e  47.09565
    2  a f  93.00538
    3  a g  18.38478
    4  a h  70.26379
    5  b e  43.01163
    6  b f  97.04638
    7  b g  13.34166
    8  b h  65.00000
    9  c e  59.16925
       etc...
    

    值不同,因为我使用了pointDistance 的平毕达哥拉斯距离。

    【讨论】:

      猜你喜欢
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      相关资源
      最近更新 更多