【发布时间】:2017-03-30 15:13:32
【问题描述】:
我想计算 (lat,lon) 坐标对之间的距离,如下例所示: Calculating distances from latitude and longitude coordinates in R
但使用 dplyr 来加快处理速度,并使用 geosphere 中的 distCosine 函数。
这个函数只接受大小为 2 的向量,我发现唯一可行的方法是:
p <- data.frame(lat=runif(6,-90,90), lon=runif(6,-180,180),lat2=runif(6,-90,90), lon2=runif(6,-180,180) )
p$dist <- sapply(1:nrow(p), function(x) distCosine(c(p$lon[x], p$lat[x]), c(p$lon2[x], p$lat2[x]) ) )
我已经尝试过使用 dplyr:
p %>% rowwise() %>% mutate(dist2prev = distCosine(c(lon, lat), c(lon2, lat2)))
p %>% group_by(1:n()) %>% mutate(dist2prev = distCosine(c(lon, lat), c(lon2, lat2)))
但错误总是一样的:
Wrong length for a vector, should be 2
知道为什么 dplyr 在那里没有成功吗?
【问题讨论】:
-
按原样为我工作
-
这也有效:
p %>% mutate(dist2prev = distCosine(cbind(lon, lat), cbind(lon2, lat2)))