G'day All,
我有两组点数据,一组具有24个位置,另一组具有〜16,000。我想计算从24个点到16,000个点的距离。使用R栅格数据包中的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
很抱歉打扰您,我们将不胜感激。
提前致谢。
亚当
您每次迭代都会用零长度的矢量覆盖结果。在循环外声明变量:
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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句